How Func Delegates Work in LINQ

A practical example demonstrating how Func delegates work in LINQ.

Step-by-step thought process

  1. Understand what Func delegates are and how they relate to LINQ.
  2. Choose a real-world scenario involving data processing.
  3. Implement a LINQ query using Func delegates to solve the problem.
  4. Explain how the Func delegate is used in the LINQ query.

Key points to consider

  • Func delegates allow for flexible function definitions in LINQ queries.
  • They enable lambda expressions to be passed as parameters to LINQ methods.
  • Func delegates are particularly useful for defining predicates and transformation functions in LINQ queries.

Practical Example

Let's say we have a list of employees with various attributes, and we want to filter them based on certain criteria and perform some transformations. We'll use Func delegates to define these operations within our LINQ query.

internal class Program
{
    private static void Main()
    {
        List<Employee> employees = new List<Employee>
        {
            new Employee { Name = "John Doe", Age = 30, Salary = 50000m },
            new Employee { Name = "Jane Smith", Age = 25, Salary = 60000m },
            new Employee { Name = "Bob Johnson", Age = 35, Salary = 70000m },
            new Employee { Name = "Alice Brown", Age = 28, Salary = 55000m }
        };

        // Define Func delegates for filtering and transformation
        Func<Employee, bool> isSenior = emp => emp.Age >= 30;
        Func<Employee, decimal> calculateBonus = emp => emp.Salary * 0.10m;

        // LINQ query using Func delegates
        var result = employees.AsQueryable()
                              .Where(isSenior)
                              .Select(emp => new
                              {
                                  Name = emp.Name,
                                  Age = emp.Age,
                                  Salary = emp.Salary,
                                  Bonus = calculateBonus(emp)
                              })
                              .OrderByDescending(x => x.Bonus);

        foreach (var employee in result)
        {
            Console.WriteLine($"{employee.Name}: {employee.Age} years old, Salary: ${employee.Salary}, Bonus: ${employee.Bonus}");
        }
    }
}

internal class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public decimal Salary { get; set; }
}

Output

Output

Explanation

  1. We define two Func delegates
    • isSenior: Takes an Employee object and returns a boolean indicating if the employee is senior (age >= 30).
    • calculateBonus: Takes an Employee object and returns the calculated bonus based on the salary.
  2. In our LINQ query, we use these Func delegates
    • Where(isSenior): Filters the employees who are seniors.
    • Select(...): Transforms each employee into an anonymous type, including the calculated bonus.
  3. The OrderByDescending(x => x.Bonus) uses another lambda expression to sort the results by the bonus amount.
  4. This example demonstrates how Func delegates enable flexible and reusable operations within LINQ queries, allowing us to separate the logic for filtering, transforming, and sorting data.


Similar Articles