[英]How to copy a subset of a list using generics and reflection
我需要將一個項目的子集從一個列表復制到另一個。 但是,我不知道列表中包含哪種項目-即使所傳遞的對象是列表。
我可以通過以下代碼查看對象是否為列表
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
}
我看不到的是如何到達列表中的單個對象,因此可以將所需的對象復制到新列表中。
大多數列表類型實現非通用的System.Collections.IList
:
IList sourceList = myDataSource as IList;
if (sourceList != null)
{
myTargetList.Add((TargetType)sourceList[0]);
}
您也可以using System.Linq;
並執行以下操作:
IEnumerable sourceList = myDataSource as IEnumerable;
if (sourceList != null)
{
IEnumerable<TargetType> castList = sourceList.Cast<TargetType>();
// or if it can't be cast so easily:
IEnumerable<TargetType> convertedList =
sourceList.Cast<object>().Select(obj => someConvertFunc(obj));
myTargetList.Add(castList.GetSomeStuff(...));
}
您編寫的代碼不會告訴您類型是否為列表。
您可以做的是:
IList list = DataSource as IList;
if (list != null)
{
//your code here....
}
這將告訴您數據源是否實現IList
接口。
另一種方法是:
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
if (t.ToString() == string.Format("System.Collections.Generic.List`1[{0}]", elementType))
{
//your code here
}
}
((IList) DataSource)[i]
如果實際上是列表,則將從列表中獲取第i
個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.