Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a list of a generic type

Tags:

c#

I need to loop through a list where the type is not known at compile-time. How to do that? The following code fails at runtime, conversion not allowed:

    Type objType = dataObject.GetType();
    List<string> strList = new List<string>();

    foreach (PropertyInfo prop in objType.GetProperties())
    {
        var val = prop.GetValue(dataObject);

        if (prop.PropertyType.Name.StartsWith("List"))   // Is there a better way?
        {
            foreach (object lval in (List<object>) val)  // Runtime failure (conversion not allowed)
            {
                strList.Add(lval.ToString());
            }
        }
        ...
like image 495
Gerard Avatar asked Oct 18 '25 01:10

Gerard


2 Answers

If you don't know the type, then : generics may not be the best option:

IList list = val as IList; // note: non-generic; you could also
                           // use IEnumerable, but that has some
                           // edge-cases; IList is more predictable
if(list != null)
{
    foreach(object obj in list)
    {
        strList.Add(obj.ToString());
    }
}
like image 187
Marc Gravell Avatar answered Oct 19 '25 16:10

Marc Gravell


Just wanted to add something to what has already been said:

Your logic is flawed because List<int> (for example) is not a subclass of List<object>. List<T> is not covariant in its type parameter.

If it was, it would be legal to do this:

List<object> listOfObjects = new List<int>();
listOfObjects.Add("a string");

Read this to learn more about covariance/contravariance in C#:

http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

like image 44
dcastro Avatar answered Oct 19 '25 17:10

dcastro