Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach List with unknown item type

Tags:

c#

I need to go through List. I do not know in advance what type of element List contains the List I get as an object.

void anyMethod(object listData, Func<object, string> callback)
{
    foreach (object item in (List<object>)data)
    {
        string value = callback(item);
        doSomething(value)
    }
};
...
List<MyObject> myList = something();
anyMethod(myList, obj => (MyObject)obj.Name)
...
List<AnotherObject> myList = somethingAnother();
anyMethod(myList, obj => (AnotherObject)obj.foo + (AnotherObject)obj.bar)
...

I need something he does as DropDownList when the process DataSource. Thanks for your help.

like image 962
Murdej Ukrutný Avatar asked Aug 05 '11 07:08

Murdej Ukrutný


1 Answers

You could try this:

void anyMethod(object listData, Func<object, string> callback)
{
    IEnumerable enumerable = listData as IEnumerable;
    if(enumerable == null)
        throw new InvalidOperationException("listData mist be enumerable");
    foreach (object item in enumerable.OfType<object>())
    {
        string value = callback(item);
        doSomething(value)
    }
};

However, if you actually call this method with a strongly typed list (such as List<YourType>) you can use generics better:

void anyMethod<T>(IEnumerable<T> listData, Func<T, string> callback)
{
    foreach (T item in listData)
    {
        string value = callback(item);
        doSomething(value)
    }
};

which is a lot cleaner.

like image 93
Jamiec Avatar answered Oct 17 '22 06:10

Jamiec