0

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.

1

3 Answers 3

1

You want Any.

var filteredLocations = 
       model.Where(m => m.LocationsCategories
            .Any(c => categoriesToLoad.Contains(c.PlaceCategoryId)));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

You can do somthing like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.