我有课程:
public class Person
{
public string Name{get;set;}
public bool IsMarried{get;set;}
public List<Child> Children { get; set; }
}
public class Child
{
public bool Greater5 { get; set; }
public List<MyColor> ListColor { get; set; }
}
public class MyColor
{
public string History { get; set; }
public string Type { get; set; }
}
我想获取IsMarried = true且Children.Greater5 = true的所有人的列表字符串(MyColor.Type,它们不为空)。 我可以通过以下方式实现这一目标:
List<Person> list = personList.Where(l => l.IsMarried == true).ToList();
List<Child> childList = list.SelectMany(c => c.Children).Where(test => test.Greater5 == true).ToList();
List<string> wantedList= childList.SelectMany(test => test.ListColor.Where(c => !String.IsNullOrEmpty(c.Type)).Select(t => t.Type)).ToList();
但我想知道是否可以使用Linq实现更简单?
答案 0 :(得分:2)
您可以链接SelectMany
以拼合嵌套的子项。
List<string> wantedList = personList
.Where(person => person.IsMarried)
.SelectMany(person => person.Children
.Where(child => child.Greater5)
.SelectMany(child => child.ListColor
.Where(color => !String.IsNullOrEmpty(color.Type))
.Select(color => color.Type)))
.ToList();
答案 1 :(得分:1)
如果您看起来“更简单”,也可以使用查询语言:
List<string> wantedList = (from person in personList where person.IsMarried
from child in person.Children where child.Greater5
from color in child.ListColor where !string.IsNullOrEmpty(color.Type)
select color.Type).ToList();