Asked by:
what is advantage of useing Ienumerable over foreach loop in C#

Question
-
User87195929 posted
Hi All
i am little confusing over Ienumerable which is used for iterate the collection,
the same iteartion can be done with foreach loop like
ArrayList list = new ArrayList(); list.Add("1"); list.Add(2); list.Add("3"); list.Add('4'); foreach (object s in list) { Console.WriteLine(s); }
andList<string> List = new List<string>();
List.Add("Sourav");
List.Add("Ram");
List.Add("shyam");
List.Add("Sachin");
foreach (string name in List )
{
Console.WriteLine(name);
}
Console.ReadLine();
Tuesday, May 1, 2018 2:18 AM
All replies
-
User1120430333 posted
IEnumerable is for read only over a collection.
www.claudiobernasconi.ch/2013/07/22/when-to-use-ienumerable-icollection-ilist-and-list/
An example of this is this. You used a Linq query in an ORM like Entity Framework and you came back with a collection result using IEnumerable. You can read the collection numerous times without the iteration going back to the database to build each object t again populated from the database, Or you could numerios sub Linq queries agaist the collection without the objects in the collection being built again from the database.
As opposed to you doing the Linq query against the database to read and build the objects loding them into a List<T>.
You iterate over the List <T> with the connection to the database still open, then on each iteration in a for loop over the collection, the object is going to built again from the read from the database.
So in this case if the query loaded 100,000 objects into the collection with 100,000 reads from the database, the loop is going back again to read the 100,000 records again from the database, resulting in 200,000 reads when it should have been only 100,000 reads.
Of course if you close the connection to the database before looping on the List<T> in this senario, they are disconnected objects that can't be reread from the database..
Tuesday, May 1, 2018 3:00 AM -
User1724605321 posted
Hi siddangoud,
I saw you are suing ArrayList in first sample . ArrayList simply stores object references. And List<T> implements the generic IEnumerable<T> interface and can be used easily in LINQ (without requiring any Cast or OfType call). You'd better not use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.
Best Regards,
Nan Yu
Tuesday, May 1, 2018 3:53 AM -
User-369506445 posted
hi
List<T>
is a generic class. It supports storing values of a specific type without casting to or fromobject
(which would have incurred boxing/unboxing overhead whenT
is a value type in theArrayList
case).ArrayList
simply storesobject
references. As a generic collection,List<T>
implements the genericIEnumerable<T>
interface and can be used easily in LINQ (without requiring anyCast
orOfType
call).ArrayList
belongs to the days that C# didn't have generics. It's deprecated in favor ofList<T>
. You shouldn't useArrayList
in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.List<T>
should generally be preferred overArrayList
- faster for value types as it avoids boxing.
- strongly typed elements
If you want lists you expose to callers to be immutable, this is supported by both
List<T>
andArrayList
:List<T>.AsReadOnly() ArrayList.ReadOnly(ArrayList list);
Tuesday, May 1, 2018 5:07 AM -
User87195929 posted
Hi My question is like this
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);A code
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
foreach (int age in age_IEnumerable)
{
Console.WriteLine(age);
}B code
//foreach (int k in ages)
//{
// Console.WriteLine(k);
//}
Console.ReadLine();bot A code and B code print the
10
20
30
40
50
what is special about B code
Tuesday, May 1, 2018 5:31 AM -
User1724605321 posted
Hi siddangoud ,
You can see the differences from here :
https://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work
Best Regards,
Nan Yu
Tuesday, May 1, 2018 5:39 AM -
User-369506445 posted
There is no such a type that is always better to return. It's a decision you should make based on your design/performance/etc goals.
IEnumerable<T>
is nice to use when you want to represent sequence of items, that you can iterate over, but you don't want to allow modifications(Add, Delete etc).IList<T>
gives you everything you could get usingIEnumerable<T>
, plus operations that give you more control over a collection: Add, Delete, Count, Index access etc.List<T>
is a concrete implementation ofIList<T>
. I would say that almost always it's better to exposeIList<T>
interface from your methods rather thatList<T>
implementation. And it's not just about lists - it's a basic design principle to prefer interfaces over concrete implementations.Ok, now about non-generic versions
IEnumerable, IList, List
: They actually came from very early versions of .NET framework, and life is much better using generic equivalents.And few words about performance:
IEnumerable<T>
(withIEnumerator<T>
) is actually an iterator which allows you to defer some computations until later. It means that there is no need to allocate memory right away for storing amounts of data(of course, it's not the case when you have, say, array behind iterator). You can compute data gradually as needed. But it means that these computations might be performed over and over again(say, with everyforeach
loop). On the other hand, with List you have fixed data in memory, with cheap Index and Count operations. As you see, it's all about compromiseOne important difference between IEnumerable and List (besides one being an interface and the other being a concrete class) is that IEnumerable is read-only and List is not.
So if you need the ability to make permanent changes of any kind to your collection (add & remove), you'll need List. If you just need to read, sort and/or filter your collection, IEnumerable is sufficient for that purpose.
So in your practical example, if you wanted to add the four int one at a time, you'd need List. But if you were instantiating your collection all at once, you could use IEnumerable.
Tuesday, May 1, 2018 5:50 AM