Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply lambda expression for specific indices in list c#

Tags:

c#

lambda

linq

I am new to lambda expression and I have problem to convert parts of code which involves indices of list inside the loop to equivalent lambda expression.

Example 1: Working with different indices inside one list

List<double> newList = new List<double>();
for (int i = 0; i < list.Count - 1; ++i)
{
     newList.Add(list[i] / list[i + 1]);
}

Example 2: Working with indices from two lists

double result = 0;
for (int i = 0; i < list1.Count; ++i)
{
    result += f(list1[i]) * g(list2[i]);
}

How to write equivalent lambda expressions?

like image 356
Dejan Avatar asked Feb 12 '23 19:02

Dejan


1 Answers

A lambda expression is something that looks like {params} => {body}, where the characteristic symbol is the => "maps to." What you are asking for are typically referred to as LINQ query expressions, which come in two styles:

  • The functional style of query is typically a sequence of chained calls to LINQ extension methods such as Select, Where, Take, or ToList. This is the style I have used in the examples below and is also the much-more prevalent style (in my experience).

  • The "language integrated" style (*) uses built-in C# keywords that the compiler will turn into the functional style for you. For example:

    var query = from employee in employeeList
                where employee.ManagerId == 17
                select employee.Name;
    
                    | compiler
                    v rewrite
    
    var query = employeeList
        .Where(employee => employee.ManagerId == 17)
        .Select(employee => employee.Name);
    

Example 1:

var newList = Enumerable.Range(0, list.Count - 1)
    .Select(i => list[i] / list[i + 1])
    .ToList();

Example 2:

var result = Enumerable.Zip(list1.Select(f), list2.Select(g), (a, b) => a * b).Sum();

(*) I'm not actually sure this is the official name for it. Please correct me with the proper name if you know it.

like image 136
Timothy Shields Avatar answered Feb 15 '23 09:02

Timothy Shields