ProfK
ProfK

Reputation: 51114

Type Constraint on foreach using LINQ extensions

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 lambda for the type check. I can't find it again, can anyone suggest how this was achieved?

Upvotes: 3

Views: 628

Answers (2)

Charlie Flowers
Charlie Flowers

Reputation: 17457

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
}

Upvotes: 3

laktak
laktak

Reputation: 60093

Are you looking for this?

public static IEnumerable<TResult> OfType<TResult>(
    this IEnumerable source
)

Upvotes: 8

Related Questions