Peter H
Peter H

Reputation: 901

Obtain an array from an Object

I have the following class definition.

public class people
{
    public string first_name { get; set; }
    public string last_name  { get; set; }
    public DateTime date_of_birth  { get; set; }
}

I've then created an array of people as follows:

    people[] the_people = new people[3];
    the_people[0].first_name="Tony";
    the_people[0].last_name="Carrot";
    the_people[0].date_of_birth=new DateTime(1959-03-16);
    the_people[1].first_name="Joe";
    the_people[1].last_name="Tomato";
    the_people[1].date_of_birth=new DateTime(1963-06-2);
    the_people[2].first_name="Tarina";
    the_people[2].last_name="Wends";
    the_people[2].date_of_birth=new DateTime(1982-11-22);

How can I store the first_names of the_people object in a new string array such that an output like the following is obtained. Is this possible via linq

string[] the_peoples_first_names=new string[3] {"Tony","Joe","Tarina"}; 

Similarly how would I obtain an array of date times to store the date of births of all people in a separate DateTime array.

Upvotes: 0

Views: 70

Answers (2)

vcsjones
vcsjones

Reputation: 141588

What you are trying to do can be done with LINQ. What you are basically asking for is a projection.

MSDN describes a projection as this:

Projection refers to the operation of transforming an object into a new form that often consists only of those properties that will be subsequently used. By using projection, you can construct a new type that is built from each object. You can project a property and perform a mathematical function on it. You can also project the original object without changing it.

So we want to project the objects in your the_people array into a new array. The documentation recommends using the Select LINQ operator:

var the_people_names = the_people.Select(p => p.first_name);

What goes inside of the Select is a delegate, often in the form of a lambda expression or anonymous delegate.

But we aren't quite there yet. Select is just a deferred evaluation that creates an enumerable sequence. It does not return an array. To create an array, we use .ToArray():

var the_people_names_array = the_people.Select(p => p.first_name).ToArray();

You can use this approach to any property of people class, including the date of birth.

You can learn more about LINQ on MSDN on the LINQ about page.

Upvotes: 6

Rufus L
Rufus L

Reputation: 37020

var firstNames = the_people.Select(p => p.first_name).ToArray();
var dates_of_birth = the_people.Select(p => p.date_of_birth).ToArray();

Upvotes: 4

Related Questions