c# - 如何从列表 linq C# 的列表中获取列表 <string>

标签 c# linq list

我有类(class):

  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 来实现更简单?

最佳答案

您可以链接 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();

关于c# - 如何从列表 linq C# 的列表中获取列表 <string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42511960/

相关文章:

c# - 获取 GeometryModel3D 的名称

c# - 在列表中查找重复项

list - 从 lisp 中的列表中删除一个元素

c - 如何将整数分配给c中的指针?

list - Ant 中使用列表的并行作业

c# - Visual Studio 2015 空白应用程序(通用 Windows): CS0731

c# - 我怎样才能让一些代码行只运行一次

c# - 获取注册表项值的最简单方法

c# - 使用 linq 将共享点列表数据绑定(bind)到下拉列表

c# - 展平一个列表,其中一个属性是另一个对象列表