简体   繁体   中英

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 :

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]如果实际上是列表,则将从列表中获取第i个元素。

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