11

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.

3 Answers 3

30

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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

1 Comment

+1 for demonstrating, but personally I'd probably still use LINQ - as it's arguably more idiomatic these days, and will be more flexible in the face of either changing requirements or changing input type. I'd use Array.ConvertAll in performance-sensitive code, or using .NET 2.0 of course.
1

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

2 Comments

You can make your setup code considerably simpler using object and collection initializers :)
You are of course right Jon (aren't you always haha). If my browser had refreshed I would have saw that you and Marc had already answered and I wouldn't have bothered. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.