WPF Linq a collection to include or exclude items

Posted by  jayprakash sharma
 2054  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?

  1. Re: WPF Linq a collection to include or exclude items

    Hi Jayprakash,

    You xaml might be like this:

    <ComboBox x:Name="cmb1"
    <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)

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