从ICollection中获取一些元素

时间:2016-07-22 17:29:47

标签: c#

如何在不知道收集类型的情况下从System.Collections.ICollection获取一定数量的元素?

伪代码

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 };

collection = collection.Take(2);

/* collection == new[] { 8, 9 }; */

当可枚举

时,您通常可以使用System.Linq.Take执行此操作

3 个答案:

答案 0 :(得分:2)

您必须先Cast<T>()这些值。 Linq(Take())仅适用于泛型类型:

        System.Collections.ICollection collection = new[] { 8, 9, 10, 12 };

        collection = collection.Cast<int>().Take(2).ToList();

        /* collection == new[] { 8, 9 }; */

答案 1 :(得分:1)

您可以制作自己的非通用扩展方法。

public static class ExtensionMethods
{
    public static IEnumerable Take(this IEnumerable @this, int take)
    {

        var enumerator = @this.GetEnumerator();
        try
        {
            for (int i = 0; i < take && enumerator.MoveNext(); i++)
            {
                yield return enumerator.Current;
            }
        }
        finally
        {
            var disposable = enumerator as IDisposable;
            if(disposable != null)
                disposable.Dispose();
        }
    }
}

class Program
{
    public static void Main(string[] args)
    {
        System.Collections.ICollection collection = new[] { 8, 9, 10, 12 };

        var result = collection.Take(2);
        foreach (var item in result)
        {
            Console.WriteLine(item);
        }
        Console.ReadLine();

    }
}

答案 2 :(得分:-1)

只是添加一种不同的方法

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 };
var _collection = collection as IEnumerable<int>;
var result = _collection.Take(3);

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 };
var enunmerator = collection.GetEnumerator();
int count = 0;
while (enunmerator.MoveNext() && count < 3)
     {
                Console.WriteLine(enunmerator.Current);
                count++;
     }
相关问题