tags:

views:

153

answers:

2

I have seen a method somewhere here on SO to restrict items returned from a foreach loop to a certain type, using, if I remember correctly, LINQ extensions on IEnumerable and a lamda for the type check. I can't find it again, can anyone suggest how this was achieved?

+7  A: 

Are you looking for this?

public static IEnumerable<TResult> OfType<TResult>(
    this IEnumerable source
)
chris
+2  A: 

You could do this with a call to the Where extension method, as follows:

foreach(var x in theCollection.Where(i => i.GetType() == typeof(DesiredType))
{
     // Do something to x
}

But this is so useful that it is built into the .NET framework, and that is what Chris is pointing out above. IEnumerable has an extension method called OfType, documented here.

To use it, you'd do something like this:

foreach(var x in theCollection.OfType<int>())
{
     // Do something to x
}
Charlie Flowers
Note that it's not exactly the same - calling GetType() and then comparing with the equality operator will behave differently in inheritance situations. The "is" operator (i.e. Where(i => i is DesiredType)) is closer to OfType.
Jon Skeet
Yes, that's right. OfType asks the question "Can this be cast to that?", so it's more like the IsAssignableFrom() method on Type.
Charlie Flowers