How can I make a cumulative filter with LINQ?

This is my method, I am filtering by only one, I need them to be cumulative

private IQueryable<PublicationModel> FilterByTreatmentStatus(IQueryable<PublicationModel> selectedData, int? filterTreatmentOption)
        {
            if (filterTreatmentOption.HasValue)
            {
                switch (filterTreatmentOption)
                {
                    case (int)PublicationTreatStatus.NotTreated:
                        return selectedData.Where(x => x.PublicationStatus == 0);
                    case (int)PublicationTreatStatus.Treated:
                        return selectedData.Where(x => x.PublicationStatus == 1);
                    case (int)PublicationTreatStatus.TreatedWithoutProvidence:
                        return selectedData.Where(x => x.PublicationStatus == 2);
                    default:
                        return selectedData;
                }
            }

            return selectedData;
        }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here you go – work with flags, so your enum can hold multiple values

[Flags]
public enum FilterTreatmentOption
{
    NotTreated = 1,
    Treated = 2,
    TreatedWithoutProvidence = 4
}


private IQueryable<PublicationModel> FilterByTreatmentStatus(IQueryable<PublicationModel> selectedData, FilterTreatmentOption filterTreatmentOption)
{
    if (filterTreatmentOption.HasFlag(PublicationTreatStatus.NotTreated))
        selectedData = selectedData.Where(x => x.PublicationStatus == 0);
    if (filterTreatmentOption.HasFlag(PublicationTreatStatus.Treated))
        selectedData = selectedData.Where(x => x.PublicationStatus == 1);
    if (filterTreatmentOption.HasFlag(PublicationTreatStatus.TreatedWithoutProvidence))
        selectedData = selectedData.Where(x => x.PublicationStatus == 2);
    return selectedData;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x