Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an ICollection of Thing. Thing has a string property Name. I would like to get an array of all Name in my ICollection. I know I can do this by iterating over the collection and building the array, but is there a neater way to do this with lambda notation?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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 :)

share|improve this answer
    
Thanks - the reason I want an array of string is to implement the method GetRolesForUser for my RoleProvider ... I'm not anticipating any big arrays being returned –  tacos_tacos_tacos Jun 1 '13 at 17:05
    
@tacos_tacos_tacos: Right - if you definitely want a string array, then the first one is what you're after. –  Jon Skeet Jun 1 '13 at 17:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.