东西比.ToArray()更好的给力LINQ输出枚举 [英] Something better than .ToArray() to force enumeration of LINQ output

查看:83
本文介绍了东西比.ToArray()更好的给力LINQ输出枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ工作的对象,有一个功能,其中在某些情况下,我需要在调用之前修改基础集合聚合(...),然后返回到原来的状态之前的功能可按返回的结果汇总(...)。我现在的code看起来是这样的:

I'm working with LINQ to objects and have a function where in some cases I need to modify the underlying collection before calling Aggregate(...) and then return it to its original state before the funciton returns the results of Aggregate(...). My current code looks something like this:

bool collectionModified = false;
if(collectionNeedsModification)
{
    modifyCollection();
    collectionModified = true;
}

var aggregationResult = from a in
                            (from b in collection
                             where b.SatisfysCondition)
                             .Aggregate(aggregationFunction)
                        select a.NeededValue;

if(collectionModified)
    modifyCollection();

return aggregationResult;

不过,由于写的,如果我修改集合,我会得到错误的结果,因为我把收集回来的原始状态之前 aggregationResult 枚举和LINQ结果是懒惰的评估。我目前的解决方案是使用 .ToArray()在我的LINQ查询是这样的:

However, as written, if I modify the collection, I will get the wrong result because I'm putting the collection back in its original state before aggregationResult is enumerated and LINQ results are lazy-evaluated. My current solution is to use .ToArray() on my LINQ query like this:

var aggregationResult = (from a in
                            (from b in collection
                             where b.SatisfysCondition)
                             .Aggregate(aggregationFunction)
                         select a.NeededValue).ToArray();

结果数组的大小永远是小(小于100项),这样存储/处理时间不是问题。这是处理我的问题的最好方法,还是有更好的办法来迫使一LINQ查询的评价?

The size of the resulting array will always be small (< 100 items) so memory / processing time is not a concern. Is this the best way to handle my problem, or is there a better way to force the evaluation of a LINQ query?

推荐答案

只是为了检查我理解你 - 你基本上要遍历所有的结果,只是为了强迫任何副作用发生

Just to check I understand you - you basically want to iterate through all of the results, just to force any side effects to take place?

副作用一般是一个坏主意precisely因为事情更难理解与这种逻辑。说了这么多,最简单的方法来做到这一点并强制全面的评估很可能只是通过它迭代:

Side effects are generally a bad idea precisely because things are harder to understand with this kind of logic. Having said that, the easiest way to do it and force full evaluation is probably to just iterate through it:

foreach (var result in aggregationResult) ;

另外,您可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.lastordefault.aspx">LastOrDefault()避免所有参与的ToArray复制()。 计数()会好起来的,只要结果不实施的IList&LT; T&GT; (其中涉及短切)

Alternatively you could use LastOrDefault() to avoid all the copying involved in ToArray(). Count() will be okay so long as the result doesn't implement IList<T> (which involves a short-cut).

这篇关于东西比.ToArray()更好的给力LINQ输出枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆