开发者

Retrieve an array of a property from an array of objects

Assume the following class:

class Person
{
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

Lets say that I have a list or an array of Person object. Is there a way using LINQ to retrieve FirstName property from all the array elements and return an array of string. I have a feeling that I have seen something like that before.

Hope that开发者_如何学编程 the question makes sense.


Sure, very easily:

Person[] people = ...;
string[] names = people.Select(x => x.FirstName).ToArray();

Unless you really need the result to be an array though, I'd consider using ToList() instead of ToArray(), and potentially just leaving it as a lazily-evaluated IEnumerable<string> (i.e. just call Select). It depends what you're going to do with the results.


If you have an array, then personally, I'd use:

Person[] people = ...
string[] names = Array.ConvertAll(people, person => person.FirstName);

here; it avoids a few reallocations, and works on more versions of .NET. Likewise:

List<Person> people = ...
List<string> names = people.ConvertAll(person => person.FirstName);

LINQ will work, but isn't actually required here.


Try this:

List<Person> people = new List<Person>();
people.Add(new Person()
    {
        FirstName = "Brandon",
        LastName = "Zeider"
    });
people.Add(new Person()
{
    FirstName = "John",
    LastName = "Doe"
});

var firstNameArray = people.Select(p => p.FirstName).ToArray();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜