linq - 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.
解决方案
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();
推荐阅读
- jenkins - Jenkins jar vs dockerfile
- r - 分配行名称时出现“级别 1 没有此类索引”错误
- ios - 如何在 UITextField 中允许表情符号
- python - 使用python从MySQL数据库中检索图像
- hosting - 网站主机不见了 | 恢复旧网站
- mysql - 创建提取字符串 sql 的新列
- c# - 在 ASP.NET MVC 中使用 C# 推送通知
- c# - HttpWebRequest 在 c# 中返回错误,适用于简单的 php 示例
- python - Tensorflow 对象检测 API:检测到特定类时将 GPIO 引脚设为高电平
- jenkins - Jenkins X 在预览环境中使用机密