Paul S Chapman
Paul S Chapman

Reputation: 832

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.

Upvotes: 1

Views: 1528

Answers (3)

herzmeister
herzmeister

Reputation: 11287

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(...));
}

Upvotes: 2

Itay Karo
Itay Karo

Reputation: 18286

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
        }
    }

Upvotes: 1

recursive
recursive

Reputation: 86084

((IList) DataSource)[i] will get the ith element from the list if it is in fact a list.

Upvotes: 0

Related Questions