【问题标题】:Get list of child class from list of parent class [closed]从父类列表中获取子类列表[关闭]
【发布时间】:2016-07-08 10:02:27
【问题描述】:

我有 2 节课:

public class Foo
{
    public String Name{get; set;}
    public Bar BarValue {get;set;}
}

public class Bar
{
    public string Value{get; set;}
}

我还有一个List<Foo>。如何从List<Foo> 获取List<Bar>

【问题讨论】:

  • 请尝试澄清您的问题。您的第一部分(大约 2 个课程)看起来与您的第二部分(关于列表)没有联系,而且问题本身也完全不清楚。
  • @YakovL 哇,我没见过。 SO 编辑器在这种大括号'' 中隐藏单词

标签: c# linq collections


【解决方案1】:

不完全确定我理解了你的问题,但如果我理解了:

据我了解,您有一个 Foos 列表,并且您想要这些 Foos 中的所有 Bar 对象。对吧?

List<Foo> foos = new List<Foo>();    
List<Bar> bars = foos.Select(foo => foo.BarValue).ToList();

【讨论】:

    【解决方案2】:

    即使您没有参考 Linq 扩展方法 (using system.linq;),您仍然可以使用经典方式:

    List<Foo> foos = new List<Foo>();
    
    List<Bar> bars = new List<Bar>();
    
    foreach (Foo f in foos)
    {
        bars.Add(f.BarValue);
    }
    

    或者(在文件顶部添加using system.linq; 之后):

    List<Bar> bars = foos.Select(f => f.BarValue).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      相关资源
      最近更新 更多