简体   繁体   中英

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)
    {
    }
}

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.

I re-read your question and it seems that you are receiving a dataset which is ALREADY a list OR a DataSet, but it is cast to an IEnumerable. In this case, simply do

IList myList = (IList)datasource //will throw exception if invalid

or

IList myList = datasource as IList //mylist will be null if conversion cannot be made

To answer your question 'how i can get the original Type and not set a object type?'.

Every type in .NET framework contains GetType method to fetch the type of the specified object. You can use it before ToList method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM