[英]How to copy a subset of a list using generics and reflection
I need to copy a sub set of items from one list to another. 我需要将一个项目的子集从一个列表复制到另一个。 However I do not know what kind of items are in the list - or even if the object being passed is a list.
但是,我不知道列表中包含哪种项目-即使所传递的对象是列表。
I can see if the object is a list by the following code 我可以通过以下代码查看对象是否为列表
t = DataSource.GetType();
if (t.IsGenericType)
{
Type elementType = t.GetGenericArguments()[0];
}
What I cannot see is how to get to the individual objects within the list so I can copy the required objects to a new list. 我看不到的是如何到达列表中的单个对象,因此可以将所需的对象复制到新列表中。
Most list types implement the non-generic System.Collections.IList
: 大多数列表类型实现非通用的
System.Collections.IList
:
IList sourceList = myDataSource as IList;
if (sourceList != null)
{
myTargetList.Add((TargetType)sourceList[0]);
}
You could also be using System.Linq;
您也可以
using System.Linq;
and do the following: 并执行以下操作:
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(...));
}
The code you wrote will not tell you if the type is a list. 您编写的代码不会告诉您类型是否为列表。
What you can do is: 您可以做的是:
IList list = DataSource as IList;
if (list != null)
{
//your code here....
}
this will tell you if the data source implements the IList
interface. 这将告诉您数据源是否实现
IList
接口。
Another way will be: 另一种方法是:
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.