Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to Select properties of class to return 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?

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

Thanks.

like image 531
Jon Avatar asked Jan 31 '11 12:01

Jon


People also ask

Does LINQ work with IEnumerable?

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> .

What does select in LINQ return?

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.

What is the return type of IEnumerable?

IEnumerable interface Returns an enumerator that iterates through the collection.

Does LINQ select return new object?

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.


1 Answers

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 
});
like image 195
Darin Dimitrov Avatar answered Sep 19 '22 07:09

Darin Dimitrov