SoFunction
Updated on 2025-04-06

In-depth understanding of the uses of C# Lambda expressions

If we want to take out the options that are odd numbers from an integer array, there are many ways to implement them. We use the following three implementations to understand the uses of Lambda expressions.

Method 1: Naming method
Copy the codeThe code is as follows:

public class Common
{
public delegate bool IntFilter(int i);
public static List<int> FilterArrayOfInt(int[] ints, IntFilter filter)
{
var lstOddInt = new List<int>();
foreach (var i in ints)
{
if (filter(i))
{
(i);
}
}
return lstOddInt;
}
}

Copy the codeThe code is as follows:

public class Application
{
public static bool IsOdd(int i)
{
return i % 2 != 0;
}
}

Called:
Copy the codeThe code is as follows:

var nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNums = (nums, );
foreach (var item in oddNums)
{
(item); // 1,3,5,7,9
}

Method 2: Anonymous method
Copy the codeThe code is as follows:

var oddNums = (nums, delegate(int i) { return i % 2 != 0; });

Method 3: Lambda Expression
Copy the codeThe code is as follows:

var oddNums = (nums, i => i % 2 != 0);

Obviously, using Lambda expressions makes the code more concise.