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?
I have tried SortedList.Select(x=>x.MyProperty, x.AnotherProperty)
but it doesnt work.
Thanks.
The IEnumerable<T> interface is central to LINQ. All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> .
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
IEnumerable interface Returns an enumerator that iterates through the collection.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With