Select Method
The query method which is the direct equivalent of the select clause is the Select method. The Select method allows you to project the results of the query. We can use the Select method by passing a selector predicate which can be supplied using a lambda expression. As an example of the Select method, the following is a simple use of it where it retrieves every item in a collection. Consider the people variable is a collection of Person object.
var result = people.Select(p => p);
A lambda expression is passed as the selector predicate for the method. The lambda expression has a single parameter p which will hold every Person object in the collection, and the right side of the lambda expression specifies what will be selected, in this case, the Person object itself. The following are more examples of using the Select method. The following are more varieties of using the Select method with different lambda expressions:
1. Select the FirstName of every person from people.
var firstNames = people.Select(p => p.FirstName);
2. Select the combined FirstName and LastName of each person to form their fullname.
var fullNames = people.Select(p => p.FirstName + " " + p.LastName);
3. Create an anonymous type that contains new property FullName which is the combined FirstName and LastName of each person.
var annonymous = people.Select(p => new { FullName = p.FirstName + " " + p.LastName } );
Another overload of the Select method accepts a lambda expression which has two parameters, the first one is the queried element, and the second one is the index of that queried element from the data source.
var personsWithIndex = people.Select((p, i) => new { Person = p, Index = i });
The following is its equivalent LINQ query:
var personsWithIndex = from p in people
select new { Person = p, Index = people.IndexOf(p) };
You can then print values of each person including their index.
foreach (var p in personsWithIndex)
{
Console.WriteLine(String.Format("[{0}] {1}", p.Index, p.Person.FirstName));
}
[0] John [1] Mark [2] Lisa
You can use the LINQ query syntax for a cleaner more readable code or you can directly call the LINQ methods using the query method syntax if you prefer to use lambda expressions.