Boolor
Boolor

Reputation: 45

LINQ in C#. why use IEnumerable<T>?

I'm learning LINQ in C# now. All sources, which i saw all uses IEnumerable<T> on left hand. why they use this and don't other types?

Upvotes: 0

Views: 160

Answers (5)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

In case of linq the queries you do on object are not executed immediately. The execution is deferred until iterations to improve the performance. Which means when you do,

var filtered = something.where(st=>st.data == mydata);

Compiler does not execute the query and retrieve the objects. So, all you can do on filtered object is iterate. Other operations (like add, remove etc) does not make sense at this point. And IEnumerable provides the perfect interface to serve this purpose.

Upvotes: 0

Brij Raj Singh - MSFT
Brij Raj Singh - MSFT

Reputation: 5113

By definition IEnumerable is "Exposes an enumerator, which supports a simple iteration over a non-generic collection" - since all you get from a query are usually objects of certain type, which are having rows (arrays in generic sense), it makes more sense to use an IEnumerable<T> to help iterate through the returned data.

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx

Upvotes: 2

Krishnraj Rana
Krishnraj Rana

Reputation: 6656

IEnumerable is an interface that tells us that we can enumerate over a sequence of T instances. If you need to perform some action for each object in a collection, this is preferable choice.

As per the MSDN IEnumerable

Exposes an enumerator, which supports a simple iteration over a non-generic collection

I also suggest you to go thru this CodeProject link

Upvotes: 2

RKS
RKS

Reputation: 1410

Two reasons for this.

  1. IEnumerable is an interface for which no instance can be created. So, it is on the left-side.
  2. All the resources which you enumerate in LINQ implement this interface.

Also, this is used when you just want to read an enumeration using an iterator and not do any modifications to it.

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Because all collections are implementing IEnumerable<T> therefore LINQ methods can be used with all collections.LINQ is designed to operate on collections so probably they choose to use IEnumerable<T> interface because it is common interface for all collection types.

Upvotes: 1

Related Questions