Select is a LINQ functionality to define a data format of the query results.
Each of below examples is presented in C# with both Lambda and Query expression.
Let’s create a Person class.
1 2 3 4 5 6 |
public class Person { public string Forename { get; set; } public string Surname { get; set; } public DateTime DateOfBirth { get; set; } } |
And collection of people which we query with LINQ expressions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var people = new List<Person>() { new Person() { Forename = "John", Surname = "Smith", DateOfBirth = new DateTime(1980, 6, 14) }, new Person() { Forename = "Bob", Surname = "Williams", DateOfBirth = new DateTime(1974, 2, 21) }, new Person() { Forename = "Chris", Surname = "Jones", DateOfBirth = new DateTime(1990, 10, 4) } }; |
1. Select single value
Query collection to get forenames only.
Lambda expression:
1 |
var items = people.Select(x => x.Forename); |
Query expression:
1 2 |
var items = from p in people select p.Forename; |
Print to screen:
1 2 |
foreach (var item in items) Console.WriteLine(item); |
Result:
1 2 3 |
John Bob Chris |
2. Select anonymous type
Query collection to get anonymous type objects containing surname and year of birth.
Lambda expression:
1 2 3 4 5 6 7 |
var items = people.Select( x => new { Surname = x.Surname, YearOfBirth = x.DateOfBirth.Year } ); |
Query expression:
1 2 3 4 5 6 |
var items = from p in people select new { Surname = p.Surname, YearOfBirth = p.DateOfBirth.Year }; |
Print to screen:
1 2 |
foreach (var item in items) Console.WriteLine(item.Surname + ", " + item.YearOfBirth); |
Result:
1 2 3 |
Smith, 1980 Williams, 1974 Jones, 1990 |
3. Select existing type
Query collection to get Person objects with upper-cased forenames and surnames.
Lambda expression:
1 2 3 4 5 6 7 8 |
var items = people.Select( x => new Person() { Forename = x.Forename.ToUpper(), Surname = x.Surname.ToUpper(), DateOfBirth = x.DateOfBirth } ); |
Query expression:
1 2 3 4 5 6 7 |
var items = from p in people select new Person() { Forename = p.Forename.ToUpper(), Surname = p.Surname.ToUpper(), DateOfBirth = p.DateOfBirth }; |
Print to screen:
1 2 |
foreach (var item in items) Console.WriteLine(item.Forename + " " + item.Surname); |
Result:
1 2 3 |
JOHN SMITH BOB WILLIAMS CHRIS JONES |