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!
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();
Use the ToList() Method to Convert an IEnumerable to a List in C# Enumerable. ToList(source); The method ToList() has one parameter only.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With