Friday, September 24, 2010

Use Linq to filter UIElements in Silverlight

Hi all

here are i am to share you the power of linq on general basis.

target is to hide all the popup controls in silverlight under the root control canvas.

Traditional code would be.

int count = this.RootCanvas.Children.Count;
List < Popup > list = new List < Popup > ();
for (int i = 0; i < count; i++)
{
if(this.RootCanvas.Children[i].GetType().Equals(new Popup().GetType())
{
list.Add((Popup) this.RootCanvas.Children[i]);
}
}

in linq

this.RootCanvas.Children.Where < UIElement > (popup = > popup.GetType().Equals(new Popup().GetType())).Cast < Popup > ().ToList < Popup > ().ForEach(popup = > { popup.IsOpen = false; });

Just a one line.

No comments:

Post a Comment