Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can convert System.Collection.IEnumerable to List<T> in c#? [duplicate]

Tags:

c#

sql

ado.net

How I can convert System.Collection.IEnumerable to list in c#? Actually I am executing a store procedure that is giving me ResultSets in System.Collection.IEnumerable and I want to convert that result set to c# List<User>.

Note I don't want to use any loop. Is there a way of type casting!

like image 990
Ali Nafees Avatar asked Feb 24 '17 05:02

Ali Nafees


People also ask

Can you convert IEnumerable to List?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

How do I get IEnumerable to a List?

Use the ToList() Method to Convert an IEnumerable to a List in C# Enumerable. ToList(source); The method ToList() has one parameter only.

What is ToList () in C#?

LINQ ToList() Method In LINQ, the ToList operator takes the element from the given source, and it returns a new List. So, in this case, input would be converted to type List.

Why do we use ToList () in C#?

ToList creates a new List internally, with the List constructor. So we can replace its usage (for converting an array) with the constructor directly. First example. This program creates an array with an array initializer.


1 Answers

You can use the following:

IEnumerable myEnumerable = GetUser();
List<User> myList = myEnumerable.Cast<User>().ToList();

As Lasse V. Karlsen suggest in his comment instead of Cast<User> you can also use OfType<User>();

If your IEnumerable is generic by default which I don't think because of your namespace in question: System.Collection.IEnumerable you could easily use:

IEnumerable<User> myEnumerable = GetUser();
List<User> myList = myEnumerable.ToList();
like image 118
Sebi Avatar answered Oct 19 '22 07:10

Sebi