C# 加速LINQ对象查询
我正在尝试加快以下LINQ对象查询的速度:C# 加速LINQ对象查询,c#,linq,C#,Linq,我正在尝试加快以下LINQ对象查询的速度: var setOfCodes = codeList1 .SelectMany(q => q.Codes) .Union(codeList2.SelectMany(q => q.Codes) .Union(codeList3.SelectMany(q => q.Codes) .ToList(); 在哪里 IE:输出一个列表,其中包含出现在codeListX中的所有代码 有没有更快的方法呢?你可以这样写:
var setOfCodes = codeList1
.SelectMany(q => q.Codes)
.Union(codeList2.SelectMany(q => q.Codes)
.Union(codeList3.SelectMany(q => q.Codes)
.ToList();
在哪里
IE:输出一个列表,其中包含出现在codeListX
中的所有代码
有没有更快的方法呢?你可以这样写:
var setOfCodes = new[] { codeList1, codeList2, codeList3 }
.SelectMany(x => x)
.SelectMany(x => x.Codes)
.Distinct()
.ToList();
两点……第一,如果您在提问时至少发布可编译代码,那就太好了。这要周到得多。第二,是什么让你觉得它慢?你分析过它吗?什么才算快?@DavidL抱歉,这里的代码是我实际使用的代码的简化版本。至于它为什么慢,这些
codeListsX
在展平时,在一个日期范围内每天包含约10-100个代码。随着日期范围的增加,此代码返回的时间大幅增加。我在考虑加快速度。作为参考,在我的开发系统上,大约500个代码需要1秒的时间才能生成一个唯一的列表。不可编译不是:)。这里真正的罪魁祸首是工会。完全避免这种情况,正如肖伊在下面的回答中所说的那样,因为你不再需要生产数量不断增加的产品,所以效率要高得多。该死,没想到这会快得多。作为参考,我的方法给我1200毫秒,而这个方法给我100毫秒。
public Item {
public List<int> Codes = new List<int>();
}
var codeList1 = new List<Item> {
new Item {
Codes = new List<int> {
100,
105,
110
}
},
new Item {
Codes = new List<int> {
100,
110,
115
}
},
};
var codeList2 = new List<Item> {
new Item {
Codes = new List<int> {
150,
155,
160
}
},
new Item {
Codes = new List<int> {
150,
155,
170
}
},
};
100, 105, 110, 115, 150, 155, 160, 170
var setOfCodes = new[] { codeList1, codeList2, codeList3 }
.SelectMany(x => x)
.SelectMany(x => x.Codes)
.Distinct()
.ToList();