WPF Linq a collection to include or exclude items

Total Post:117

Points:821
WPF 
WPF
 1612  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. 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();

      Modified On Apr-03-2018 06:19:11 AM

Answer

NEWSLETTER

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