1

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?

Jack A.
  • 4,245
  • 1
  • 20
  • 34

1 Answers1

1

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.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • That's exactly what I'm looking for. I knew it made sense for something like that to exist, just missed it when looking. – Jack A. Sep 30 '18 at 21:29