相关疑难解决方法(0)

计算IOrderedEnumerable而不消耗它

我想做什么,短版:

var source = new[]{2,4,6,1,9}.OrderBy(x=>x);
int count = source.Count; // <-- get the number of elements without performing the sort
Run Code Online (Sandbox Code Playgroud)

长版:

要确定IEnumerable中元素的数量,必须迭代所有元素.这可能是一项非常昂贵的操作.

如果可以将IEnumerable转换ICollection,则可以快速确定计数而无需迭代.LINQ Count()方法自动执行此操作.

函数myEnumerable.OrderBy()返回一个IOrderedEnumerable.一个IOrderedEnumerable显然不能被强制转换为ICollection的,因此调用COUNT()会消耗整个事情.

但排序不会改变元素的数量,IOrderedEnumerable必须保持对其源的引用.因此,如果该源是ICollection,则应该可以从IOrderedEnumerable中确定计数而不消耗它.

我的目标是有一个库方法,它接受带有n个元素的IEnumerable,然后例如检索位置为n/2的元素;

我想避免迭代IEnumerable两次只是为了得到它的计数,但我也想避免创建一个不必要的副本,如果可能的话.


这是我想要创建的函数的框架

public void DoSomething(IEnumerable<T> source)
{
    int count; // What we do with the source depends on its length

    if (source is ICollection)
    {
        count = …
Run Code Online (Sandbox Code Playgroud)

c# linq reflection performance ienumerable

6
推荐指数
1
解决办法
2566
查看次数

标签 统计

c# ×1

ienumerable ×1

linq ×1

performance ×1

reflection ×1