1

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.

3 Answers 3

2

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(...));
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Yikes! What's with the string comparison? The proper way would be t.GetGenericTypeDefinition() == typeof(List<>)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.