LINQ selection by type of an object
Solution 1:
You can use the OfType
Linq method for that:
var ofTypeA = collection.OfType<A>();
Regarding your unwillingness to loop throught the collection, you should keep in mind that Linq does not do magic tricks; I didn't check the implementation of OfType
, but I would be surprised not to find a loop or iterator in there.
Solution 2:
For completeness, here is the source code of Enumerable.OfType<T>
.
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) {
if (source == null) throw Error.ArgumentNull("source");
return OfTypeIterator<TResult>(source);
}
static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source) {
foreach (object obj in source) {
if (obj is TResult) yield return (TResult)obj;
}
}
You can see that it lazily evaluates the source stream.
Solution 3:
You can use the OfType extension method for this
IEnumerable<A> filteredToA = list.OfType<A>();
IEnumerable<B> filteredToB = list.OfType<B>();