views:

266

answers:

1

I've got a list of elements of a certain class. This class contains a field.

class Foo {public int i;}
List<Foo> list;

I'd like to extract the field from all items in the list into a new list.

List<int> result = list.ExtractField (e => e.i); // imaginary

There are surely multiple ways to do that, but I did not find a nice-looking solution yet. I figured linq might help, but I was not sure how exactly.

+6  A: 

Just:

List<int> result = list.Select(e => e.i).ToList();

or

List<int> result = list.ConvertAll(e => e.i);

The latter is more efficient (because it knows the final size to start with), but will only work for lists and arrays rather than any arbitrary sequence.

Jon Skeet
Darn, twice pipped already this morning ;-p
Marc Gravell
Thanks Jon, Marc, that was fast. :)
mafutrct