Query collection by type / cast elements to C# with Example



Query collection by type / cast elements to C# with Example

type 
interface IFoo { } 
class Foo : IFoo { } 
class Bar : IFoo { } 
var item0 = new Foo(); 
var item1 = new Foo(); 
var item2 = new Bar(); 
var item3 = new Bar(); 
var collection = new IFoo[] { item0, item1, item2, item3 }; 
Using OfType 
var foos = collection.OfType(); // result: IEnumerable with item0 and item1 
var bars = collection.OfType(); // result: IEnumerable item item2 and item3 
var foosAndBars = collection.OfType(); // result: IEnumerable with all four items 
Using Where 
var foos = collection.Where(item => item is Foo); //  result: IEnumerable  with  item0  and  item1 
var bars = collection.Where(item => item is Bar); //  result: IEnumerable  with  item2  and  item3 
Using Cast 
var bars = collection.Cast(); // throws InvalidCastException on the 1st item 
//  throws  InvalidCastException  on  the  3rd  item 
var foos = collection.Cast(); 
// OK 
var foosAndBars = collection.Cast(); 
 

0 Comment's

Comment Form