首页 > 解决方案 > Linq query to select all records that have sub records that match all values in an array of values?

问题描述

I have a table that contains records that have a related table that may have multiple records for each of the main records. This is a table of flags. i.e.

MyRecord can have multiple subrecords Flag1, Flag4, Flag7

I am trying to create a Linq query that will return records that have all the flags I specify.

This is code of what I am trying to do

var flags = new List<string>() { "Flag1"};
db.Contents.Include(f=>f.Flags)
.Where(a => flags.All(b=>a.Flags.Any(f =>f.Name==b)));

The above almost works but returns records with Flag1 along with records that have Flag1,Flag4 and Flag1,Flag4,Flag7. I need to return only records that have the requested flags set.

标签: linq

解决方案


var answer = db.Contents.Include(x => x.Flags)
      .Where(x => 
               x.Flags.Select(y => y.Name).Distinct().Count() == flags.Count 
               && 
               flags.All(y => x.Flags.Any(z => z.Name == y)))
      .ToList();

推荐阅读