WPF LINQ A COLLECTION TO INCLUDE OR EXCLUDE ITEMS

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
WPF 
WPF
 1357  View(s)
Ratings:
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?

  1. ezra heywood

    Post:145

    Points:1019
    Re: WPF Linq a collection to include or exclude items

    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();

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!