Freely convert between List<T> and IEnumerable<T>
List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();
A List<T>
is an IEnumerable<T>
, so actually, there's no need to 'convert' a List<T>
to an IEnumerable<T>
.
Since a List<T>
is an IEnumerable<T>
, you can simply assign a List<T>
to a variable of type IEnumerable<T>
.
The other way around, not every IEnumerable<T>
is a List<T>
offcourse, so then you'll have to call the ToList()
member method of the IEnumerable<T>
.
A List<T>
is already an IEnumerable<T>
, so you can run LINQ statements directly on your List<T>
variable.
If you don't see the LINQ extension methods like OrderBy()
I'm guessing it's because you don't have a using System.Linq
directive in your source file.
You do need to convert the LINQ expression result back to a List<T>
explicitly, though:
List<Customer> list = ...
list = list.OrderBy(customer => customer.Name).ToList()