1110
1110

Reputation: 6839

How to filter a list where I need multiple dynamic filter parameters

I have a list of objects (Locations). Every location can have multiple categories. I have a list of integers (CategoryId's). Based on that I need to filter locations:

List<int> categoriesToLoad = new List<int>();
// fill list
var allLocations = locationRepository.GetLocations().Where(...
var filteredLocations = from m in model
                             where categoriesToLoad.Contains(m.LocationCategories.FirstOrDefault() == null ? -1 : m.LocationCategories.FirstOrDefault().PlaceCategoryId)
                             select m;

This works only for one category, I don't know how to fix code to compare all categories that are attached to location.

Upvotes: 0

Views: 608

Answers (3)

Joshua Honig
Joshua Honig

Reputation: 13215

You want Any.

var filteredLocations = 
       model.Where(m => m.LocationsCategories
            .Any(c => categoriesToLoad.Contains(c.PlaceCategoryId)));

Upvotes: 1

david.s
david.s

Reputation: 11403

You can do somthing like this:

var filteredLocations = locationRepository
                            .GetLocations()
                            .Where(l => l.LocationCategories.Any(x => categoriesToLoad.Contains(x.PlaceCategoryId));

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14522

Try to replace this:

var filteredLocations = from m in model
                        where categoriesToLoad.Contains(m.LocationCategories.FirstOrDefault() == null ? -1 : m.LocationCategories.FirstOrDefault().PlaceCategoryId)
                        select m;

with this:

var filteredLocations = from m in model
                        where m.LocationCategories.Any(x => categoriesToLoad.Contains(x.PlaceCategoryId)
                        select m;

Though I don't really understand fully what you're trying to do and whats the logic of your application, so it is possible that all I've said is crap.

Upvotes: 1

Related Questions