Export (0) Print
Expand All

How to: Use Lambda Expressions in a Query (C# Programming Guide)

You do not use lambda expressions directly in query syntax, but you do use them in method calls, and query expressions can contain method calls. In fact, some query operations can only be expressed in method syntax. For more information about the difference between query syntax and method syntax, see Query Syntax and Method Syntax in LINQ (C#).

The following example demonstrates how to use a lambda expression in a method-based query by using the Enumerable.Where standard query operator. Note that the Where method in this example has an input parameter of the delegate type Func<TResult> and that delegate takes an integer as input and returns a Boolean. The lambda expression can be converted to that delegate. If this were a LINQ to SQL query that used the Queryable.Where method, the parameter type would be an Expression<Func<int,bool>> but the lambda expression would look exactly the same. For more information on the Expression type, see System.Linq.Expressions.Expression.

class SimpleLambda
{
    static void Main()
    {

        // Data source. 
        int[] scores = { 90, 71, 82, 93, 75, 82 };

        // The call to Count forces iteration of the source 
        int highScoreCount = scores.Where(n => n > 80).Count();

        Console.WriteLine("{0} scores are greater than 80", highScoreCount);

        // Outputs: 4 scores are greater than 80            
    }
}

The following example demonstrates how to use a lambda expression in a method call of a query expression. The lambda is necessary because the Sum() standard query operator cannot be invoked by using query syntax.

The query first groups the students according to their grade level, as defined in the GradeLevel enum. Then for each group it adds the total scores for each student. This requires two Sum operations. The inner Sum calculates the total score for each student, and the outer Sum keeps a running, combined total for all students in the group.

private static void TotalsByGradeLevel()
{
    // This query retrieves the total scores for First Year students, Second Years, and so on. 
    // The outer Sum method uses a lambda in order to specify which numbers to add together. 
    var categories =
    from student in students
    group student by student.Year into studentGroup
    select new { GradeLevel = studentGroup.Key, TotalScore = studentGroup.Sum(s => s.ExamScores.Sum()) };

    // Execute the query.    
    foreach (var cat in categories)
    {
        Console.WriteLine("Key = {0} Sum = {1}", cat.GradeLevel, cat.TotalScore);
    }
}
/*
     Outputs: 
     Key = SecondYear Sum = 1014
     Key = ThirdYear Sum = 964
     Key = FirstYear Sum = 1058
     Key = FourthYear Sum = 974
*/

To run this code, copy and paste the method into the StudentClass that is provided in How to: Query a Collection of Objects (C# Programming Guide) and call it from the Main method.

Show:
© 2014 Microsoft