Foreach 非常慢 C#

问题描述 投票:0回答:1

我有一个foreach,在这个foreach中我遍历一个列表,在这个foreach中我有一个条件来检查另一个有20万行的列表中是否有某些信息是字符串。

我想做得更快。

  foreach(var dto in List){
    // the problem is here
    if(anotherList.Any(d => d.id == dto.id && d.line.equals(dto.line))) 
          continue;
    }

希望能快点。

c# foreach
1个回答
0
投票

Any
的复杂度为
O(n)
,其中 n 是集合 (
anotherList
) 中的元素数量,因此您的代码的整体复杂度为
O(m*n)
,其中 m 是
List
中的元素数量。如果
id
是唯一的,那么您可以创建查找字典,该字典在一般情况下应该具有恒定的查找时间,并执行以下操作:

var dict = anotherList
  .ToDictionary(d => d.Id);

foreach(var dto in List)
{
    if (dict.TryGetValue(dto.Id, out var val) && val.line.equals(dto.line))
    {
        continue;
    }
}

这应该将复杂性降低到

O(m+n)

© www.soinside.com 2019 - 2024. All rights reserved.