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

Jon*_*Jon 10 .net c# linq .net-3.5 c#-3.0

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

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

谢谢.

Dar*_*rov 17

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

var result = SortedList.Select(x => new { 
    x.Value.MyProperty, 
    x.Value.AnotherProperty 
});
Run Code Online (Sandbox Code Playgroud)

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

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