Linq过滤嵌套列表

时间:2016-10-17 17:49:22

标签: 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"}]},

]
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这将解决您的问题,但可能有更好的方法,我也省略了一些属性,如您需要添加的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()
});

答案 2 :(得分:0)

以下逻辑可以帮助您仅过滤嵌套列表。

例如:

考虑以下类结构:

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

然后,仅过滤subEntity这样的详细信息。

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