grimsan55 grimsan55 - 1 month ago 19
C# Question

Trying to simplify LINQ expression

I'm trying to simplify a LINQ expression but no matter what i try I'm unable to get it to work

var filterProfileIds = filter.Profiles.Select(s => s.ProfileId);
var newList = new List<FileMedia>();
foreach (var item in filterProfileIds)
{
newList.AddRange(query.Where(w => w.Profiles.Select(s => s.ProfileId).Contains(item)));

}

newList.AddRange(query.Where(w => !w.Profiles.Any()));

query = newList.AsQueryable();


query is of type "FileMedia" and has a relation to Profiles.

So what i want is all the results from the query that has the same profiles that filter.profiles has AND i also want all the results from the query that doesnt have any profiles at all.

Answer

Try as the below:

var filterProfileIds = filter.Profiles.Select(s => s.ProfileId);
query = query.Where(w => 
                    !w.Profiles.Any() || 
                     w.Profiles.Any(i => filterProfileIds.Contains(i.ProfileId))
                ).ToList();