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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With