Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve an array of a property from an array of objects

Tags:

c#

linq

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.

like image 999
Skadoosh Avatar asked Jul 11 '11 14:07

Skadoosh


People also ask

How do you access the properties of an array of objects?

At which point you can access it by simply saying newJsonArray[i]. Code or whatever property inside the array you want to use.

How do you access data from an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

How do you find the value of an array of objects?

To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop.

How do you access an array inside an array?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.


3 Answers

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.

like image 153
Jon Skeet Avatar answered Sep 20 '22 16:09

Jon Skeet


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.

like image 28
Marc Gravell Avatar answered Sep 19 '22 16:09

Marc Gravell


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();
like image 40
BrandonZeider Avatar answered Sep 22 '22 16:09

BrandonZeider