Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest and most compact way to create a IEnumerable<T> or ICollection<T>?

So, many times we have a function that accepts an IEnumerable or ICollection as a parameter. In cases where we have single items, but no collection to hold them, we must create a collection before passing them to the function, like:

T o1, o2, o3;
Foo(new T[] { o1, o2, o3 });

I've always created an array or a list, like I've done in the last example. But I wonder, is there a more elegant way to create the required IEnumerable or ICollection?

It would be quite cool, if one could do this:

Foo({ o1, o2, o3 });

And the compiler would create the most abstract possible collection that would satisfy the needs of IEnumerable or ICollection (depending on which one the function accepts).

Anyhow, how you would pass o1, o2 and o3 to an IEnumerable or ICollection parameters?

like image 798
Ashley Simpson Avatar asked Sep 26 '09 14:09

Ashley Simpson


People also ask

Should I use ICollection or IEnumerable?

IEnumerable contains only GetEnumerator() method, like read-only iterate. ICollection is one step ahead of IEnumerable. If we want some more functionality like Add or remove element, then it is better to go with ICollection because we cannot achieve that with IEnumerable. ICollection extends IEnumerable.

What is IEnumerable T?

IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.

What is the difference between ICollection and IList?

ICollection<T> is an interface that exposes collection semantics such as Add() , Remove() , and Count . Collection<T> is a concrete implementation of the ICollection<T> interface. IList<T> is essentially an ICollection<T> with random order-based access.

How do I create an instance of ICollection?

ICollection is an interface, you can't instantiate it directly. You'll need to instantiate a class that implements ICollection ; for example, List<T> . Also, the ICollection interface doesn't have an Add method -- you'll need something that implements IList or IList<T> for that.


1 Answers

The current version of C# (3) supports a notation without explicit type, i.e.

Foo(new [] { o1, o2, o3 })

to create an array. There’s also Linq’s Enumerable.Range to create a continuous range of numbers. Everything else has to be implemented. In the spirit of Java:

public static IEnumerable<T> AsList<T>(params T[] values) {
    return values;
}

to be called like this:

Foo(Enumerable.AsList(o1, o2, o3));
like image 99
Konrad Rudolph Avatar answered Oct 06 '22 08:10

Konrad Rudolph