Foreach List with unknown item type
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);
doSomethi开发者_开发百科ng(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.
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.
If DoSomething()
is a static method, you can use a generic extension method (as List<T>
itself is generic anyway):
public static void AnyMethod<T>(this List<T> listData, Func<T, string> callback)
{
foreach (T item in listData)
{
string value = callback(item);
DoSomething(value);
}
}
Then call it like this:
List<MyObject> myList = Something();
myList.AnyMethod(obj => obj.Name);
List<AnotherObject> myList = SomethingAnother();
myList.AnyMethod(obj => obj.foo + obj.bar);
Notice you do not need to cast either.
However, if DoSomething()
is an instance method, I think you can go with Jamiec's second solution.
精彩评论