How to Use Select in LINQ - C#

This is a quick guide on how to use the Select LINQ operator, using both method and query syntax.

The Select command allows us to map each element of a sequence into a new form.

Let's take a look at an example with a simple object collection:

class UsingLinq 
{
    public static void Main (string[] args) 
    {
        var people = new List<Person>() 
        { 
            new Person() { PersonId = 1, Name = "Belinda", Age = 70 },
            new Person() { PersonId = 2, Name = "Betty",  Age = 81 },
            new Person() { PersonId = 3, Name = "Will",  Age = 18 },
            new Person() { PersonId = 4, Name = "Andy", Age = 70 },
            new Person() { PersonId = 5, Name = "Rob", Age = 15 }
        };
	}
}

class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public Person() {}

    public void Introduce() 
    {
        Console.WriteLine($"My name is {Name}, and I am {Age} years old.");
    }
}

Using Method Syntax

Using the method syntax, let's use Select to return only the name property of the Person object:

public static void Main (string[] args) 
{
	var people = new List<Person>() 
	{ 
		new Person() { PersonId = 1, Name = "Belinda", Age = 70 },
		new Person() { PersonId = 2, Name = "Betty",  Age = 81 },
		new Person() { PersonId = 3, Name = "Will",  Age = 18 },
		new Person() { PersonId = 4, Name = "Andy", Age = 70 },
		new Person() { PersonId = 5, Name = "Rob", Age = 15 }
	};

	var names = people.Select(p => p.Name); 	foreach(String name in names)	{		Console.WriteLine(name);	}}

This will give us the following output:

Belinda
Betty
Will
Andy
Rob

Using Query Syntax

We can also use the query syntax, to achieve the same outcome:

public static void Main (string[] args) 
{
	var people = new List<Person>() 
	{ 
		new Person() { PersonId = 1, Name = "Belinda", Age = 70 },
		new Person() { PersonId = 2, Name = "Betty",  Age = 81 },
		new Person() { PersonId = 3, Name = "Will",  Age = 18 },
		new Person() { PersonId = 4, Name = "Andy", Age = 70 },
		new Person() { PersonId = 5, Name = "Rob", Age = 15 }
	};

	var names = from p in people				select p.Name; 	foreach(String name in names)	{		Console.WriteLine(name);	}}

This will give us the same output:

Belinda
Betty
Will
Andy
Rob