6

我想做的,简短的版本:

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

长版:

要确定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 = source.Count(); // Great, we can use ICollection.Count
    }
    else if (source is IOrderedEnumerable)
    {
        // TODO: Find out whether this is based on an ICollection, 
        // TODO: then determine the count of that ICollection
    }
    else
    {
        // Iterating over the source may be expensive, 
        // to avoid iterating twice, make a copy of the source
        source = source.ToList();
        count = source.Count();
    }

    // do some stuff

}
4

3 回答 3

8

让我们想想这段代码实际上是什么样子的:

var source = new[]{ 2, 4, 6, 1, 9 }.OrderBy(x => x);
int count = source.Count();

它与

int count = Enumerable.Count(Enumerable.OrderBy(new[]{ 2, 4, 6, 1, 9 }, x => x));

的结果Enumerable.OrderBy(new[]{ 2, 4, 6, 1, 9 }, x => x)被传递给Count扩展。你无法避免OrderBy执行。因此它是非流式操作符,它在返回一些东西之前消耗所有源,这些东西将被传递给Count.

因此,避免遍历所有集合的唯一方法是避免OrderBy- 在排序之前对项目进行计数。


更新:您可以在任何地方调用此扩展方法OrderedEnumerable- 它将使用反射来获取包含源序列source的字段。OrderedEnumerable<T>然后检查这个序列是否是集合,并Count在不执行排序的情况下使用:

public static class Extensions
{
    public static int Count<T>(this IOrderedEnumerable<T> ordered)
    {
        // you can check if ordered is of type OrderedEnumerable<T>
        Type type = ordered.GetType();
        var flags = BindingFlags.NonPublic | BindingFlags.Instance;
        var field = type.GetField("source", flags);
        var source = field.GetValue(ordered);
        if (source is ICollection<T>)
            return ((ICollection<T>)source).Count;

        return ordered.Count();
    }
}

用法:

var source = new[]{ 2, 4, 6, 1, 9 }.OrderBy(x => x);
int count = source.Count();
于 2013-07-05T16:41:33.403 回答
0

如果您正在寻求创建一个高性能的解决方案,我会考虑创建采用集合或 IOrderedEnumerable 等的重载。所有“是”和“作为”类型检查和强制转换对你的事情都不好正在创造。

你正在重新发明轮子。linq 的“Count()”函数几乎可以满足您的需求。

另外,添加 this 关键字并使其成为一个漂亮的扩展方法,以取悦自己和其他使用代码的人。

DoSomething(this Collection source);
DoSomething<T>(this List<T> source);
DoSomething<T>(this IOrderedEnumerable<T> source);

ETC...

于 2013-07-05T16:38:13.557 回答
0

另一种方法是实现一个实现IOrderedEnumerable<T>. 然后,您可以实现类成员,使通常的 Linq 扩展方法短路,并提供一个查看原始枚举的 count 方法。

public class MyOrderedEnumerable<T> : IOrderedEnumerable<T>
{
    private IEnumerable<T> Original;
    private IOrderedEnumerable<T> Sorted;

    public MyOrderedEnumerable(IEnumerable<T> orig)
    {
            Original = orig;
            Sorted = null;
    }

    private void ApplyOrder<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer, bool descending)
    {
            var before = Sorted != null ? Sorted : Original;
            if (descending)
                    Sorted = before.OrderByDescending(keySelector, comparer);
            else
                    Sorted = before.OrderBy(keySelector, comparer);
    }

    #region Interface Implementations

    public IEnumerator<T> GetEnumerator()
    {
            return Sorted != null ? Sorted.GetEnumerator() : Original.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
            return GetEnumerator();
    }

    public IOrderedEnumerable<T> CreateOrderedEnumerable<TKey>(
            Func<T, TKey> keySelector,
            IComparer<TKey> comparer,
            bool descending)
    {
            var newSorted = new MyOrderedEnumerable<T>(Original);
            newSorted.ApplyOrder(keySelector, comparer, descending);
            return newSorted;
    }

    #endregion Interface Implementations


    //Ensure that OrderBy returns the right type. 
    //There are other variants of OrderBy extension methods you'll have to short-circuit
    public MyOrderedEnumerable<T> OrderBy<TKey>(Func<T, TKey> keySelector)
    {   
            Console.WriteLine("Ordering");
            var newSorted = new MyOrderedEnumerable<T>(Original);
            newSorted.Sorted = (Sorted != null ? Sorted : Original).OrderBy(keySelector);
            return newSorted;
    }

    public int Count()
    {
            Console.WriteLine("Fast counting..");
            var collection = Original as ICollection;
            return collection == null ? Original.Count() : collection.Count;
    }

    public static void Test()
    {
            var nums = new MyOrderedEnumerable<int>(Enumerable.Range(0,10).ToList());
            var nums2 = nums.OrderBy(x => -x);
            var z = nums.Count() + nums2.Count();
    }
}
于 2013-07-05T17:43:01.880 回答