roydukkey
roydukkey

Reputation: 3288

Take an amount of elements from ICollection

How can you take an amount of elements from System.Collections.ICollection without knowing the collection type?

Pseudo Code

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

collection = collection.Take(2);

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

You would normally be able to do this with System.Linq.Take when the enumerable

Upvotes: 1

Views: 666

Answers (3)

Scott Chamberlain
Scott Chamberlain

Reputation: 127593

You could make your own non-generic extension method.

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();

    }
}

Upvotes: 1

Saket Choubey
Saket Choubey

Reputation: 916

Just to add one different approach

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

Or

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++;
     }

Upvotes: -1

tofi9
tofi9

Reputation: 5853

You'd have to Cast<T>() the values first. Linq (Take()) only works on generic types:

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

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

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

Upvotes: 2

Related Questions