Search code examples
c#wpffilterdatagridicollectionview

Filter Criteria OR Instead of AND C# WPF


I am currently filtering a DataGrid based on the selection of a group of CheckBoxes. Criteria are added to a list of Criteria and the ICollectionView that the DataGrid is bound to is filtered appropriately.

This works OK if I want to filter on an 'AND' basis. Each job has an employee associated to it, but at the moment the filter works by saying show jobs where job.employee = employee 1 AND job.employee = employee2. This is the code at the moment, it will filter like so;

        criteria.Clear();

        if (yourJobsCheckBox.IsChecked == true)
        {
            criteria.Add(new Predicate<JobModel>(x => x.ITName == yourJobsCheckBox.Tag.ToString()));
        }

        if (danJobsCheckBox.IsChecked == true)
        {
            criteria.Add(new Predicate<JobModel>(x => x.ITName == danJobsCheckBox.Tag.ToString()));
        }

        if (emilyJobsCheckBox.IsChecked == true)
        {
            criteria.Add(new Predicate<JobModel>(x => x.ITName == emilyJobsCheckBox.Tag.ToString()));
        }

        if (adamJobsCheckBox.IsChecked == true)
        {
            criteria.Add(new Predicate<JobModel>(x => x.ITName == adamJobsCheckBox.Tag.ToString()));
        }

        JobModel job = o as JobModel;
        bool isIn = true;
        if (criteria.Count() == 0)
            return isIn;
        isIn = criteria.TrueForAll(x => x(job));
        return isIn;

This is currently filtering by jobs where ITName = tag1 AND ITName = tag2etc. etc. A job will never have more than one employee assigned to it, so inevitably as soon as the user clicks on more than one CheckBox no jobs are shown.

How can I change my filter so that instead it filters on an 'OR' basis? For example show jobs where job.employee = employee 1 OR job.employee = employee 2


Solution

  • Did you try "Any"? "Any" receives a Predicate. It determines if any element in a collection matches a certain condition.