列表对象属性的枚举器

时间:2016-11-15 20:27:58

标签: c# list oop

是否可以创建一个IEnumerable变量,将另一个List的foreach元素指向特定属性?

//...
  SomeList<classA> MainList = new SomeList<classA>();
  IEnumerable<string> InnerList = ??MainList??;
  MainList.add(new classA());
  Console.Writeline(InnerList.First());
// ->"Hello World"
//...

class classA{
  public string innerObject = "Hello World";
}

1 个答案:

答案 0 :(得分:1)

您可以通过linq:

来完成
var sampleList = new List<classA>();

var innerList = sampleList.Select(x => x.innerObject) //This creates an IEnumerable of all innerObjects in the original list