gpt4 book ai didi

c# - LINQ on HashSet 与 List 的对比

转载 作者:太空宇宙 更新时间:2023-11-03 22:33:43 24 4
gpt4 key购买 nike

我需要计算具有给定值的属性的列表/集合的元素。列表很大,我需要尽可能好的性能。我应该使用列表还是集合(当有独特的元素时)?有没有更快的方法?

int counter = myList.Where(x => x.A == myValue || x.B == myValue).Count()

对于另一个巨大的列表,这已经在 AsParallel().ForAll() 中。不,我无法改变这一点。

编辑

我已经看到了 this question它绝对不能解决我的问题,我对 (P)LINQ 查询的差异很感兴趣。

最佳答案

如果您要遍历整个集合,遍历整个列表可能会比遍历整个集合产生更好的性能,因为列表元素在内存中的分配方式(假设您使用的是 List<T>,而不是链表)。

如果您对 myList 中的相同数据执行数千次此类查询,您可以通过在 x.A 上构建三个查找表来提高性能, x.B ,以及关于 x.A == x.B 时的共同值(value):

var countByA = myList
.GroupBy(x => x.A)
.ToDictionary(g => g.Key, g => g.Count());
var countByB = myList
.GroupBy(x => x.B)
.ToDictionary(g => g.Key, g => g.Count());
var countByAandB = myList
.Where(x => x.A == x.B)
.GroupBy(x => x.A)
.ToDictionary(g => g.Key, g => g.Count());

现在可以使用 inclusion-exclusion principle 将您的查询转换为三个查找:

countByA.TryGetValue(myValue, out var counterA);
countByB.TryGetValue(myValue, out var counterB);
countByAandB.TryGetValue(myValue, out var counterAandB);
int counter = counterA + counterB - counterAandB;

关于c# - LINQ on HashSet 与 List 的对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com