[英]Convert IEnumerable in List<T>
I am creating a control that receive in datasource a DataSet or List 我正在创建一个控件,在数据源中接收DataSet或List
How i convert a IEnumerable to List in a CreateChildControls event? 我如何在CreateChildControls事件中将IEnumerable转换为List?
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. 通常会使用来自Linq的
IEnumerable<T>.ToList()
扩展方法,但在你的情况下你不能使用它(马上),因为你有非通用的IEnumerable
接口。 Sou you will have to cast it first (also using Linq): 你必须首先施放它(也使用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. 我重新阅读了您的问题,似乎您正在接收一个数据集,该数据集是ALREADY列表或DataSet,但它被转换为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. .NET框架中的每个类型都包含
GetType
方法来获取指定对象的类型。 You can use it before ToList
method. 您可以在
ToList
方法之前使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.