gpt4 book ai didi

c# - Linq 过滤嵌套列表

转载 作者:行者123 更新时间:2023-11-30 23:19:45 25 4
gpt4 key购买 nike

好的,我在下面写了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com