Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable in List<T>

I am creating a control that receive in datasource a DataSet or List

How i convert a IEnumerable to List in a CreateChildControls event?

protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
    if (dataSource is System.Data.DataSet)
    {
    }
    else if(dataSource is IList)
    {
    }
}
like image 962
Pablogrind Avatar asked Jul 25 '11 06:07

Pablogrind


People also ask

Can I 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();

Is IEnumerable better than List?

Is IEnumerable faster than List? IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.

What is the difference between IEnumerable and List in C#?

One 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.


1 Answers

Usually one would use the IEnumerable<T>.ToList() extensionmethod from Linq but in your case you can not use it (right away) because you have the non-generic IEnumerable interface. Sou you will have to cast it first (also using Linq):

datasource.Cast<object>().ToList();

No matter what you original collection actually ist, this will always succeed.

like image 134
bitbonk Avatar answered Sep 22 '22 06:09

bitbonk