views:

49

answers:

3

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.

A: 

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
        }
    }
Itay
I think - should be =
recursive
it should - thanks :)
Itay
Yikes! What's with the string comparison? The proper way would be `t.GetGenericTypeDefinition() == typeof(List<>)`
Kirk Woll
@Kirk: Damn - I didn't know it could be done :)
Itay
A: 

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

recursive
+1  A: 

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