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 Name
s, 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 Contact
s and create my own Array. I could be naive, but I just thought there might be a Dictionary
ish way to get at it in one开发者_运维技巧 line of code.
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.
You could use LINQ:
Contact[] contacts = GetContacts();
string[] names = contacts.Select(c => c.Name).ToArray();
精彩评论