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.
|
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:
|
var items = people.Select(x => x.Forename);
|
Query expression:
|
var items = from p in people
select p.Forename;
|
Print to screen:
|
foreach (var item in items)
Console.WriteLine(item);
|
Result:
2. Select anonymous type
Query collection to get anonymous type objects containing surname and year of birth.
Lambda expression:
|
var items = people.Select(
x => new
{
Surname = x.Surname,
YearOfBirth = x.DateOfBirth.Year
}
);
|
Query expression:
|
var items = from p in people
select new
{
Surname = p.Surname,
YearOfBirth = p.DateOfBirth.Year
};
|
Print to screen:
|
foreach (var item in items)
Console.WriteLine(item.Surname + “, “ + item.YearOfBirth);
|
Result:
|
Smith, 1980
Williams, 1974
Jones, 1990
|
3. Select existing type
Query collection to get Person objects with upper-cased forenames and surnames.
Lambda expression:
|
var items = people.Select(
x => new Person()
{
Forename = x.Forename.ToUpper(),
Surname = x.Surname.ToUpper(),
DateOfBirth = x.DateOfBirth
}
);
|
Query expression:
|
var items = from p in people
select new Person()
{
Forename = p.Forename.ToUpper(),
Surname = p.Surname.ToUpper(),
DateOfBirth = p.DateOfBirth
};
|
Print to screen:
|
foreach (var item in items)
Console.WriteLine(item.Forename + ” “ + item.Surname);
|
Result:
|
JOHN SMITH
BOB WILLIAMS
CHRIS JONES
|
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW