Home > DeveloperSection > Forums > WPF Linq a collection to include or exclude items
jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    December-09-2013 11:37 PM

 WPF WPF 
Ratings:


 1 Reply(s)
 990  View(s)
Rate this:

I have 3 comboboxes that the user can select a value. On the SelectionChanged event of each combobox will filter out an observablecollection that would only populate another collection based on the values. The comboboxes contains a blank at the top for the user to select not to apply the filter on that column.

Is there a simple way to use linq to do this?



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    December-10-2013 12:06 AM

Hi Jayprakash,

You xaml might be like this:

<ComboBox x:Name="cmb1" SelectionChanged="Selector_OnSelectionChanged">

<ComboBox x:Name="cmb2" SelectionChanged="Selector_OnSelectionChanged">

<ComboBox x:Name="cmb3" SelectionChanged="Selector_OnSelectionChanged">

 

And code of the handler:

var someCollection = new List<int>(); // some your collection

// stubs

Expression<Func<int, bool>> predicate1 = (x) => true;

Expression<Func<int, bool>> predicate2 = (x) => true;

Expression<Func<int, bool>> predicate3 = (x) => true;

 

// real predicates

if (cmb1.SelectedIndex >= 0)

    predicate1 = (x) => x == (int)cmb1.SelectedValue;

if (cmb2.SelectedIndex >= 0)

    predicate2 = (x) => x == (int)cmb2.SelectedValue;

if (cmb3.SelectedIndex >= 0)

    predicate3 = (x) => x == (int)cmb3.SelectedValue;

 

// eval and out

lstBox.Items = someCollection.Where(predicate1)

                             .Where(predicate2)

                             .Where(predicate3)

                             .ToList();


Don't want to miss updates? Please click the below button!

Follow MindStick