Apply function to LINQ query

In my last project i have been working with linq to do some cool stuff with objects. Like manipulating controls and specially doing any sort of filtering. I gotta say, linq is great for this. Many of you have in some point or another use a for each loop to filter the objects based on their properties; well, this all can be done easier using linq.

Ex. Closing windows using LinQ to object and expressions.  I am filtering all the windows for the current app and at the same time closing them. Calling the Count() function force the linq expression to apply the function and close the window.

private int closeWin(Window w)
{
 w.Close();
 return 0;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{      
 System.Linq.Expressions.Expression<Func<Window, double?>> calc = (w) => closeWin(w);

 var childWindows = (from w in Application.Current.Windows.OfType<Window>()
      where w.Name != “mainWin”
      select calc.Compile().Invoke(w));
 var count = childWindows.Count();
 
}

~ by ajhorus on October 24, 2008.

Leave a Reply