c# - Linq 过滤嵌套列表

标签 c# linq

好的,我在下面写了 LINQ to Entities 查询(足够接近下面显示的我的 c# 查询)

var itemss = filteredstudents
.Where(x => x.SubjectTypes.Any(y => y.SubjectItem.Any(z => z.Name  == value1))).ToList();

仍然没有什么问题,因为当 SubjectItem 类型有两个元素并且其中一个与 value1 匹配时。它仍然返回两者。它应该只返回匹配的记录。我知道问题出在 Any 上,但不确定 Any 应该替换成什么?

foreach (StudentDTO student in filteredstudents)
{
    bool valid = true;
    foreach (SubjectTypes subjectType in student.SubjectTypes)
    {
        string value1 = subjectType.SubjectItem.Select(x => x.value1).First();
        Guid StId = _context.Items.Where(x => x.Name == value1).FirstOrDefault();

        if (StId != null)
            valid = true;
        else
        {
            valid = false;
            _log("create log");
        }
    }
    if (valid)
        filteredstudentsWithUnits.Add(student);
}

示例输入

{"Name":"ABC",
"Age":12,
,"SubjectTypes":
[
{"Id":"1","Description":""Description","SubjectItem":[{"Id":"1","Marks":12,"Name":"aaa"}]},
{"Id":"1","Description":""Description","SubjectItem":[{"Id":"1","Marks":12,"Name":"aaa"}]},
{"Id":"1","Description":""Description","SubjectItem":[{"Id":"1","Marks":12,"Name":"bbb"}]}
]
}

预期输出

{"Name":"ABC",
"Age":12,
,"SubjectTypes":
[
{"Id":"1","Description":""Description","SubjectItem":[{"Id":"1","Marks":12,"Name":"aaa"}]},
{"Id":"1","Description":""Description","SubjectItem":[{"Id":"1","Marks":12,"Name":"aaa"}]},

]
}

最佳答案

您可以先使用 .Where 过滤列表,然后使用 .Select 投影到仅包含所需数据的新集合。像下面这样的东西可能会起作用:

var itemss = filteredstudents
    .Where(s => s.SubjectTypes.Any(st => st.SubjectItem.Any(si => si.Name  == value1)))
    .Select(s => new StudentDTO
    {
        Name = s.Name,
        Age = s.Age,
        SubjectTypes = s.SubjectTypes.Where(st => st.SubjectItem.Any(si => si.Name  == value1))
            .Select(st => new SubjectType
            {
                Id = st.Id,
                Description = st.Description,
                SubjectItem = st.SubjectItem.Where(si => si.Name == value1).ToList()
            }).ToList()
    })
    .ToList();

关于c# - Linq 过滤嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092659/

相关文章:

c# - Excel Interop - 在所有其他工作表之后添加一个新工作表

c# - MailKit:如何从 MimeMessage 本地下载所有附件

c# - 源不包含数据行

vb.net - Linq-to-Entities 聚合在外部函数中计算的列

c# - IEnumerable 有值但仍然给出 System.NullReferenceException

c# - 从字典中按标签获取按钮 c#

c# - 设置响应 ContentType 的中间件

c# - 我应该避免使用依赖注入(inject)和 IoC 吗?

c# - Odbc 连接到 .tps 数据库不工作

c# - Linq中的高级过滤