Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 606
Sebastian 506563 Avatar asked Jan 15 '14 11:01

Sebastian 506563


2 Answers

You were almost there:

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

you need to just add ToArray at the end

like image 76
Kamil Budziewski Avatar answered Nov 16 '22 02:11

Kamil Budziewski


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

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

like image 31
Avi Turner Avatar answered Nov 16 '22 02:11

Avi Turner