tags:

views:

47

answers:

2

Yeah, poorly worded question, but I really wasn't sure how to phrase it. :)

Let's say I have a simple class that looks like this:

public class Contact
{
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
}

and I have an List<> of them. Well, I'd like to be able to get a List of all Names, just like Dictionary<T,U> lets me do something like Dictionary.Keys.ToArray() and Dictionary.Values.ToArray(). Currently, I'm doing the obvious thing, which is to loop over the array of Contacts and create my own Array. I could be naive, but I just thought there might be a Dictionaryish way to get at it in one line of code.

+5  A: 

Assuming the list is named contacts, here is a linq query that should give you an array of names:

var names = (from c in contacts select c.Name).ToArray();

Note: it first creates an IEnumerable<string> then converts it to an array.

Oded
+1 BOOM. Linq wins again
fletcher
brilliant. gotta learn LINQ. :)
Dave
It should return a IEnumerable<String> first, not List<string>
LLS
@Dave: My approach to learning a technology is to learn one thing at a time and keep adding them to my toolbox. Once I hit a certain threshold, only then do I jump in head first. Then I have enough context for new concepts to stick.
Merlyn Morgan-Graham
@Dave - look here for a good learning resource for linq: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
Oded
@LLS - thanks for the correction
Oded
@Merlyn good advice, thank you.
Dave
+4  A: 

You could use LINQ:

Contact[] contacts = GetContacts();
string[] names = contacts.Select(c => c.Name).ToArray();
Darin Dimitrov