Sebastian 506563
Sebastian 506563

Reputation: 7248

How to convert list of objects with two fields to array with one of them using LINQ

It's hard for me to explain, so let me show it with pseudo code:

ObjectX
{
    int a;
    string b;
}
List<ObjectX> list = //some list of objectsX//
int [] array = list.Select(obj=>obj.a);

I want to fill an array of ints with ints from objectsX, using only one line of linq.

Upvotes: 5

Views: 1869

Answers (2)

Avi Turner
Avi Turner

Reputation: 10456

The only problem in your code is that Select returns IEnumerable.

Convert it to an array:
int[] array = list.Select(obj=>obj.a).ToArray();

Upvotes: 5

Kamil Budziewski
Kamil Budziewski

Reputation: 23117

You were almost there:

int[] array = list.Select(obj=>obj.a).ToArray();

you need to just add ToArray at the end

Upvotes: 11

Related Questions