我有两个班,物业和经理。
public class Property
{
public Manager Manager {get;set;}
}
public class Manager {
public int ID { get; set; }
public string Fullname {get; set;}
}
Property p1 = new Property{
Manager = new Manager {
ID = 1,
Fullname = "John Doe"
}
}
Property p2 = new Property{
Manager = new Manager {
ID = 1,
Fullname = "John Doe"
}
}
Property p3 = new Property{
Manager = new Manager {
ID = 2,
Fullname = "John Doe"
}
}
List<Property> properties = new List{ p1, p2, p3 }
在这个 List
的 properties
我如何确定每个物业都有相同的管理人?ID
? 如果一个或多个没有,那么我想返回 false
.
你可以使用一点 System.Linq
以确定 All
项目具有相同 Id
作为 First
项。
bool allHaveSameId = properties.All(p => p.Manager.ID == properties.First().Manager.ID);
你只需覆盖属性和经理人的Equals就可以了
public class Manager{
public int ID { get; set; }
public string Fullname {get; set;}
public override bool Equals(Manager that){
if ((obj == null) || ! this.GetType().Equals(obj.GetType())){
return false;
}else {
return this.ID == that.ID;
}
}
}
public class Property{
public Manager Manager {get;set;}
public override bool Equals(Property that){
if ((obj == null) || ! this.GetType().Equals(obj.GetType())){
return false;
}else {
return this.manager.Equals(that.Manager);
}
}
}
我想我会选择评论里链接的那种东西。
return properties.Any() && properties.All(p=>p.Manager.ID == properties[0].Manager.Id);
return properties.Select(p => p.Manager.ID).Distinct().Count() == 1;