Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何提高比较两个列表的LINQ查询的性能?_C#_Performance_Linq - Fatal编程技术网

C# 如何提高比较两个列表的LINQ查询的性能?

C# 如何提高比较两个列表的LINQ查询的性能?,c#,performance,linq,C#,Performance,Linq,下面的查询符合我的要求,但当两个列表有许多项(>30万)时,查询速度非常慢 基本上,它返回列表2中没有文档的所有人 personList1.Add(person1); personList1.Add(person2); personList2.Add(person2); personList2.Add(person3); var result = personList2 .

下面的查询符合我的要求,但当两个列表有许多项(>30万)时,查询速度非常慢

基本上,它返回列表2中没有文档的所有人

        personList1.Add(person1);
        personList1.Add(person2);

        personList2.Add(person2);
        personList2.Add(person3);

        var result = personList2
                    .Where(p2 => p2.documents
                        .Exists(d2 => !personList1
                            .Exists(p1 => p1.documents
                                .Contains(d2)
                            )
                        )
                    ).ToList();

        result.ForEach(r => Console.WriteLine(r.name));
        //Should return person3 name
班级

public class Person
{
    public string name { get; set; }
    public List<IdentificationDocument> documents { get; set; }

    public Person()
    {
        documents = new List<IdentificationDocument>();
    }
}

public class IdentificationDocument
{
    public string number { get; set; }
}
公共类人物
{
公共字符串名称{get;set;}
公共列表文档{get;set;}
公众人士()
{
文件=新列表();
}
}
公共类标识文档
{
公共字符串编号{get;set;}
}
完整代码


有人知道如何提高查询性能吗?谢谢大家!

首先将所有相关数据放入为查找而创建的结构中:

var lookup = new HashSet<string>(personList1.SelectMany(p => p.documents).Select(d => d.number));

var result = personList1.Where(p => !p.documents.Select(d => d.number).Any(lookup.Contains));
var lookup=newhashset(personList1.SelectMany(p=>p.documents.Select(d=>d.number));
var result=personList1.Where(p=>!p.documents.Select(d=>d.number).Any(lookup.Contains));

首先将所有相关数据放入一个用于查找的结构中:

var lookup = new HashSet<string>(personList1.SelectMany(p => p.documents).Select(d => d.number));

var result = personList1.Where(p => !p.documents.Select(d => d.number).Any(lookup.Contains));
var lookup=newhashset(personList1.SelectMany(p=>p.documents.Select(d=>d.number));
var result=personList1.Where(p=>!p.documents.Select(d=>d.number).Any(lookup.Contains));

为什么
John
?如果您可以更改
Person
类,请尝试将
列表
更改为
HashSet
。您可能还想覆盖
GetHashCode
。为什么
John
?如果可以更改
Person
类,请尝试将
List
更改为
HashSet
。您可能还需要覆盖
GetHashCode