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 eve开发者_开发技巧n 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
:
IList sourceList = myDataSource as IList;
if (sourceList != null)
{
myTargetList.Add((TargetType)sourceList[0]);
}
You could also be 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.
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]
will get the i
th element from the list if it is in fact a list.
精彩评论