9

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!

Sebi
  • 3,879
  • 2
  • 35
  • 62
Ali Nafees
  • 185
  • 1
  • 1
  • 7

2 Answers2

23

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();
Sebi
  • 3,879
  • 2
  • 35
  • 62
0

You should be able to just use Linq's ToList() method.

List<string> collection = myEnumCollection.ToList();
Chris Cruz
  • 1,829
  • 13
  • 15
  • This won't work because the OP ask for System.Collection.IEnumerable and not using System.Collections.Generic.IEnumerable – Sebi Feb 24 '17 at 06:05