【发布时间】:2014-03-09 11:42:59
【问题描述】:
我在 SO 上浏览过几篇文章,但找不到解决方案(针对这个特定的)。
我有一些复杂的 Linq 查询,它返回几 数千 行。我使用IEnumerable 作为结果。但后来,我需要遍历每一行,以执行一些操作。为此,我使用对ToList() 的调用将其转换。但这(我相信)正在扼杀性能,并且超时。任何优化建议/指导?如果我遗漏了什么,您可以纠正我。 (我是性能问题的新手)
这是我的代码:
IEnumerable<someModel> results = null;
results = from x in tableX ..... select xyz;
//some complex query, returning few thousands of rows.
//now converting to list:
List<someModel> MYresults = results.ToList();
number_of_records = MYresults.Distinct(new myComparer()).Count();
//row operation that I need to perform:
if(condition)
{
foreach(someModel m in MYresults)
{
m.property = m.property + someOperations();
}
}
if(somecondition)
{
return MYresults.Distinct(new someComparer()).ToList();
}
else
return MYresults.Distinct(new someComparer()).Skip(x).Take(y).ToList();
【问题讨论】:
-
为什么需要将其转换为列表来遍历项目?你应该也可以遍历
results -
您确实需要显示完整的查询,因为问题在于
ToList是否超时。 -
@Zeeshan,但无论如何调用
ToList应该不会有太大的不同。当您调用ToList时,这只是执行 LINQ 的地方。也许您可以优化您的 LINQ,但为此您需要展示它。 -
如何衡量实际花费的时间?
标签: c# performance linq ienumerable