使用 Linq 选择类的属性以返回 IEnumerable<T>

11

如果我有一个 SortedList<int, MyClass>,我想要返回该类的属性的新的IEnumerable<T>,我该怎么做?

我尝试过使用 SortedList.Select(x=>x.MyProperty, x.AnotherProperty),但它不起作用。

谢谢。


“可枚举的属性(Enumerable of properties)”应该如何呈现?你能给我们一个示例,最好是伪代码吗? - Ani
1个回答

19
你可以返回一个匿名对象:
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 {....... - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接