Sure, LINQ lets you do this very easily:
string[] names = things.Select(x => x.Name).ToArray();
Of course if you're just going to iterate over it, you don't need the ToArray
part:
IEnumerable<string> names = things.Select(x => x.Name);
Or you could create a List<string>
with ToList
:
List<string> names = things.Select(x => x.Name).ToList();
In all of these cases you could use var
instead of explicitly declaring the variable type - I've only included the type here for clarity.
Using ToList
can be very slightly more efficient than using ToArray
, as the final step in ToArray
involves copying from a possibly-oversized buffer to a right-sized array.
EDIT: Now we know you really do need an array, it would be slightly more efficient to do this yourself with a manual loop, as you know the size beforehand. I'd definitely use the first form until I knew it was a problem though :)