我想知道 C#/LINQ 是否内置了任何功能来简化以下内容:
foreach(var item in collection)
{
if (item.GetType() == typeof(Type1)
DoType1(item as Type1);
else if (item.GetType() == typeof(Type2))
DoType2(item as Type2);
...
}
类似于以下内容:
collection.ForEachType(Type1 item => DoType1(item), Type2 item => DoType2(item));
我意识到以下内容很接近:
collection.OfType<Type1>.ToList().Foreach(item => DoType1(item));
collection.OfType<Type2>.ToList().Foreach(item => DoType2(item));
但是当代码依赖于集合的顺序时它不起作用。