开发者

How to retrieve an array of a class' members from an array of that class?

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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜