tags:

views:

257

answers:

1

As an example, say I have an array of names and I want to create an array of Person objects by calling a constructor that takes string name.

class Person()
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

...

static void Main()
{
    string[] names = {"Peter", "Paul", "Mary"};
    Person[] people;

    /*  I could do this but I'm wondering if there's a better way. */
    List<Person> persons = new List<Person>();
    foreach(string name in names)
    {
        persons.Add(new Person(name));
    }

    people = persons.ToArray();
}

I've been stuck in the .Net 2.0 world for too long now and I'm trying to modernize in my current downtime...

+14  A: 
// names is string[]
Person[] people = names.Select(s => new Person(s)).ToArray();

Explanation:

Enumerable.Select is the LINQ method for projection. That is, taking a sequence of Foos and projecting them to Bars via some rule Func<Foo, Bar> that eats Foos and spits out Bars. Thus

names.Select(s => new Person(s))

is a projection of the sequence names of type IEnumerable<string> to a sequence of type IEnumerable<Person>. If you know functional programming it plays the role of map.

Now, there is a subtle point here that is worth understanding; this is almost surely one of the most important yet easily misunderstood aspects of LINQ. This is the concept of deferred execution. When we say

IEnumerable<Person> persons = names.Select(s => new Person(s));

this does not actually perform the projection (i.e., it does not yet create the instances of Person constructed using the strings in names as constructor parameters). Instead, it creates something that captures the rule of how to project the sequence names into a sequence of Person. It's only when that rule (known as an iterator) is actually executed does the projection take place.

One way to cause this execution to occur is to use the method Enumerable.ToArray which basically says iterate through the sequence and give me back the results as an array.

There are other ways to cause the execution to occur. For example

IEnumerable<Person> persons = names.Select(s => new Person(s)); 
foreach(Person p in persons) {
    Console.WriteLine(p.Name);
}

or

IEnumerable<Person> persons = names.Select(s => new Person(s)); 
Person p = persons.First();

which would execute the "first" projection (i.e., new Person(names[0])) and assign the result to p.

Of course, this doesn't even get into exactly what

s => new Person(s)

is. That's a lambda expression, and you can get an introduction to them in my answer to How does this LINQ Expression work?.

Jason
I get confused now seeing `Select` instead of `map` like in F#.
ChaosPandion
Easy enough! Thanks!!
Austin Salonen
@ChaosPandion: Yes, I would love to know why the more familiar `map` and `fold` weren't used instead of `Select` and `Aggregate`, for example.
Jason
Damn... I need another vote to give to you!
Austin Salonen
@Jason, map and fold are actually not the most familiar to most developers, most developers come from a SQL world, where aggregation and selection rule the syntax.
Tim Jarvis
@Jason...+1 for you answer though, very nice indeed.
Tim Jarvis