There are a lot of situations in Silverlight and WPF where you would like to get a list of items from a collection of a certain type. For example all textboxes in a Grid, or all customer records from a ListView.
LINQ provides us with an extension method to do this very easily, the OfType<T>() extension on IEnumerable:
public static IEnumerable<TResult> OfType<TResult>(
this IEnumerable source
)
Let me explain the use of this method thru some examples.
Say you have a grid with some textboxes, buttons and labels and you want to iterate thru the textboxes to perform some calculation. Instead of creating a foreach loop, looping thru all children of this grid and checking if this child is a textbox, let LINQ figure this out. This is how you do this:
foreach(TextBox tb in LayoutRoot.Children.OfType<TextBox>()){
//Do some stuff
}
The same thing can be done with a ListView. In this ListView there are Customers and Employees mixed together. To provide easy access to only the Customers or Employees I created readonly properties to do this.
List<Customer> Customers
{
get
{
return aList.Items.OfType<Customer>().ToList();
}
}
List<Employee> Employees
{
get
{
return aList.Items.OfType<Employee>().ToList();
}
}
Now you have an easy access to only the customers or employees in this ListView “aList”.