Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.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# 列表中同时包含两个属性的项_C#_Performance_Linq_Intersect - Fatal编程技术网

C# 列表中同时包含两个属性的项

C# 列表中同时包含两个属性的项,c#,performance,linq,intersect,C#,Performance,Linq,Intersect,我有一个对象列表X(名称为X),其属性a和b的类型位置。我还有一个位置列表y。我需要在x中查找列表y中包含a和b的所有对象 我可以使用循环和Wheres来完成,但由于这两个列表都很大,我需要一个性能非常好的解决方案。在这种情况下,有没有办法使用Intersect?还是别的什么 这里有一些伪代码 class X { Location a; Location b; } GetMatches(List<X> x, List<Location> y) { ??

我有一个对象列表
X
(名称为
X
),其属性
a
b
的类型
位置
。我还有一个位置列表
y
。我需要在
x
中查找列表
y
中包含
a
b
的所有对象

我可以使用循环和
Where
s来完成,但由于这两个列表都很大,我需要一个性能非常好的解决方案。在这种情况下,有没有办法使用
Intersect
?还是别的什么

这里有一些伪代码

class X
{
    Location a;
    Location b;
}

GetMatches(List<X> x, List<Location> y) { ?? }
X类
{
地点a;
地点b;
}
GetMatches(列表x,列表y){???}

首先将y列表转换为a

然后,获得匹配既快又容易:

private static List<X> GetMatches(List<X> x, HashSet<Location> y)
{
    return x
        .Where(item => y.Contains(item.a) && y.Contains(item.b))
        .ToList();
}
私有静态列表GetMatches(列表x,哈希集y)
{
返回x
其中(项目=>y.Contains(项目a)和&y.Contains(项目b))
.ToList();
}
使其并行以变得更快:

private static List<X> GetMatchesParallel(List<X> x, HashSet<Location> y)
{
    return x
        .AsParallel()
        .AsOrdered()
        .Where(item => y.Contains(item.a) && y.Contains(item.b))
        .ToList();
}
私有静态列表GetMatchesParallel(列表x,哈希集y)
{
返回x
.天冬酰胺()
.AsOrdered()
其中(项目=>y.Contains(项目a)和&y.Contains(项目b))
.ToList();
}

是否可以使用
哈希集
而不是
列表
?然后
Contains
方法将在
O(1)
中运行。如果您能提供@mong-zhu,那就太棒了,谢谢,我会试试。这应该是可能的。。。“我还没想过呢!”法比扬,这会让这个相当简单的问题变得很长,很难理解,而且花了我很多时间。因为我不需要一个关于工作代码的答案,而是关于如何使用的想法,所以我更喜欢一个简短易读的问题,而不是为我和读者增加额外的开销。
private static List<X> GetMatchesParallel(List<X> x, HashSet<Location> y)
{
    return x
        .AsParallel()
        .AsOrdered()
        .Where(item => y.Contains(item.a) && y.Contains(item.b))
        .ToList();
}