繁体   English   中英

加快性能-LINQ在一个LIST中获得项目,而不在另一个列表中

[英]Speed Up Performance - LINQ to get items in one LIST, that are not in another List

我有两个列表,我想返回不在另一个列表中的项目。 这是我的代码:

var Results = ListOne.Where(x => ListTwo.All(a => a.EmployeeNum != x.EmployeeNum && a.Sched != x.Sched));

这大约需要9-10秒才能完成。 ListOne大约有1200条记录,ListTwo大约有33000条记录。

使用HashSet<T> ,因为它具有O(1)搜索时间,可以提高性能,例如

var hashSet = new HashSet<T>(ListTwo.Select(x => Tuple.Create(x.EmployeeNum, x.Sched)));
var results = ListOne.Where(x => !hashSet.Contains(Tuple.Create(x.EmployeeNum, x.Sched)));

您还可以创建自己的IEqualityComparer(假设您有一个名为Employee的类):

var results = ListTwo.Except(ListOne, new EmployeeComparer());

IEqualityComparer实现:

public class EmployeeComparer : IEqualityComparer<Employee>
{
    public int GetHashCode(Employee co)
    {
        if (co == null)
        {
            return 0;
        }

        return co.EmployeeNum.GetHashCode();
    }

    public bool Equals(Employee x1, Employee x2)
    {
        if (object.ReferenceEquals(x1, x2))
        {
            return true;
        }

        if (object.ReferenceEquals(x1, null) || object.ReferenceEquals(x2, null))
        {
            return false;
        }

        return x1.EmployeeNum == x2.EmployeeNum && x1.Sched == x2.Sched;
    }
}

尝试这个

var Results = ListOne.AsParallel().Where(x => ListTwo.All(a => a.EmployeeNum != x.EmployeeNum && a.Sched != x.Sched)).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM