列表包含列表

时间:2016-06-09 19:45:43

标签: c# contains

您好我有以下列表:

 var CustomerName = new List<Customer>();
 var DummyData = new List<Customer>();

如何快速检查DameData是否包含在CustomerName中?此外,性能也很关键,因为这些列表可能包含数千个值。

1 个答案:

答案 0 :(得分:5)

蛮力方法

对DummyData变量O(N*K)

使用linq all方法
// 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
              )
          );

使用HashSet

将结果放入一个哈希集并再次使用linq&#39; All方法检查hashset是否包含项目,采用N步构建hashset和K步骤进行检查,复杂度为O(N+K)

var hs = new HashSet<Customer>(CustomerName);
DummyData.All(a=>hs.Contains(a));

您需要覆盖Equals和GetHashCode

如果您还没有覆盖这两个,但除非您想比较属性,否则您需要这样做,这也会阻止您使用哈希集方法

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);
        }
    }
}