使用LINQ to选择类返回的IEnumerable&LT的性质; T>性质、to、LINQ、IEnumerable

2023-09-03 01:26:22 作者:麻烦先生抱抱我

如果我有一个排序列表< INT,MyClass的> ,我想返回一个新的的IEnumerable< T> 我怎么做,从这个类的属性?

If I have a SortedList<int, MyClass> and I want to return a new IEnumerable<T> of properties from that class how do I do that?

我已经试过 SortedList.Select(X =&GT; x.MyProperty,x.AnotherProperty),但它不工作

I have tried SortedList.Select(x=>x.MyProperty, x.AnotherProperty) but it doesnt work.

感谢。

推荐答案

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

You could return an anonymous object:

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

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

Or if you want to use the result outside of the scope of the current method you could define a custom type:

IEnumerable<MyType> result = SortedList.Select(x => new MyType { 
    Prop1 = x.Value.MyProperty, 
    Prop2 = x.Value.AnotherProperty 
});
 
精彩推荐
图片推荐