【问题标题】:Using Linq to Select properties of class to return IEnumerable<T>使用 Linq 选择类的属性以返回 IEnumerable<T>
【发布时间】:2011-06-18 13:25:49
【问题描述】:

如果我有一个 SortedList&lt;int, MyClass&gt; 并且我想从该类返回一个新的 IEnumerable&lt;T&gt; 属性,我该怎么做?

我尝试了SortedList.Select(x=&gt;x.MyProperty, x.AnotherProperty),但它不起作用。

谢谢。

【问题讨论】:

  • “可枚举的属性”应该如何呈现?能否给我们一个示例,最好是伪代码?

标签: c# .net linq .net-3.5 c#-3.0


【解决方案1】:

你可以返回一个匿名对象:

var result = SortedList.Select(x => new { 
    x.Value.MyProperty, 
    x.Value.AnotherProperty 
});

或者如果你想使用当前方法范围之外的结果,你可以定义一个自定义类型:

IEnumerable<MyType> result = SortedList.Select(x => new MyType { 
    Prop1 = x.Value.MyProperty, 
    Prop2 = x.Value.AnotherProperty 
});

【讨论】:

  • 谢谢。正在撞墙的那一刻,忘记了 x => new {.......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2012-11-29
  • 1970-01-01
相关资源
最近更新 更多