您好我有以下列表:
var CustomerName = new List<Customer>();
var DummyData = new List<Customer>();
如何快速检查DameData是否包含在CustomerName中?此外,性能也很关键,因为这些列表可能包含数千个值。
答案 0 :(得分:5)
对DummyData变量O(N*K)
// If you override Equals and GetHashCode or are comparing by reference
DummyData.All(a=>CustomerName.Contains(a))
//If you compare by property
DummyData.All(a=>
CustomerName.Any(b=>
a.FirstName==b.FirstName &&
a.LastName == b.LastName
//repeat to include checks for all properties
)
);
将结果放入一个哈希集并再次使用linq&#39; All
方法检查hashset是否包含项目,采用N步构建hashset和K步骤进行检查,复杂度为O(N+K)
var hs = new HashSet<Customer>(CustomerName);
DummyData.All(a=>hs.Contains(a));
如果您还没有覆盖这两个,但除非您想比较属性,否则您需要这样做,这也会阻止您使用哈希集方法
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
var customer = obj as Customer;
return customer != null && Equals(customer);
}
protected bool Equals(Customer other)
{
return string.Equals(FirstName, other.FirstName) && string.Equals(LastName, other.LastName);
}
public override int GetHashCode()
{
unchecked
{
return ((FirstName?.GetHashCode() ?? 0)*397) ^ (LastName?.GetHashCode() ?? 0);
}
}
}