Linq筛选嵌套列表

本文关键字:列表 嵌套 筛选 Linq | 更新日期: 2023-09-27 18:13:28

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

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

问题不大,因为当SubjectItem类型有两个元素时,其中一个元素与value1匹配。它仍然返回两者。它应该只返回匹配的记录。我知道问题是与任何,但不确定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"}]},
]
}

Linq筛选嵌套列表

您可以先使用.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();

这将解决你的问题,但可能有更好的方法,我也省略了一些属性,如id和标记,你需要添加。

var items = filteredstudents.Select(s => new StudentDTO
{
    Name = s.Name,
    SubjectTypes = s.SubjectTypes.Select(st => new SubjectType
    {
        Description = st.Description,
        SubjectItems = st.SubjectItems.Where(si => si.Name == "AAA").ToList()
    }).Where(x => x.SubjectItems.Count > 0).ToList()
});

下面的逻辑可以帮助您只过滤嵌套列表。

为例:

考虑下面的类结构:

class EntityName { int i; string xx; List<SubEntity> subEntityName; }

然后,像这样只过滤subEntity的细节。

objEntity.SubEntityName = objEntity.SubEntityName.Where(x=>x.attrubute== "")"