Jack A.
Jack A.

Reputation: 4443

Operation to combine Where and Cast in LINQ

Is there a more succinct way to write this:

var targets = collection
    .Where(x => x is ITarget)
    .Cast<ITarget>();

It seems like there should be a way to combine the calls the Where and Cast into a single operation. However, perusing Enumerable turns up no likely candidates.

Does such a LINQ operation exist or is this the only way to do it?

Upvotes: 1

Views: 61

Answers (1)

Erik Philips
Erik Philips

Reputation: 54628

Actually you're looking for OfType<>().

Excerpt:

Filters the elements of an IEnumerable based on a specified type.

System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("Banana");

// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = fruits.OfType<string>();

Console.WriteLine("Elements of type 'string' are:");
foreach (string fruit in query1)
{
  Console.WriteLine(fruit);
}

output:

Mango

Orange

Apple

Banana

So Reading: When to use Cast() and Oftype() in Linq.

Upvotes: 1

Related Questions