In the
Introduction of LINQ post we saw what is LINQ and types of syntax used in LINQ and how to perform some operations in list of strings.
In this topic we are going to see how we can we can perform some most common operation on number or array of numbers. Some of them are
- SUM
- AVERAGE
- MINIMUM NUMBER
- MAXIMUM NUMBER
- EVEN NUMBER
To perform sum of all numbers in C#, we end up using a for loop by looping through all the numbers within the array of numbers and then add each and every number with the added number to produce the result. We are doing this for years, but using LINQ extension method we can just call an extension method “Sum()” as shown
This will produce our desired result.
Here is the complete code list which will demonstrate each and operation we listed followed by the output.
public static void WorkingWithIntLINQ()
{
int[] numbers = { 1, 2, 3, 4, 10, 12, 6, 5, 19, 22, 44 };
//Take Average of numbers
double aresult = numbers.Average();
Console.WriteLine("AVERAGE :"+ aresult);
//Sum of numbers
int sresult = numbers.Sum();
Console.WriteLine("SUM :" + sresult);
//Take minimum value from number
int min = numbers.Min();
Console.WriteLine("MINIMUM :"+min);
//Take maximum value from number
int max = numbers.Max();
Console.WriteLine("MAXIMUM :" +max);
//Get length of array (number)
int len = numbers.Length;
Console.WriteLine("LENGTH :" + len);
//Get all even numbers
Console.WriteLine("\nALL EVEN NUMBERS");
IEnumerable result= numbers.Where(x => x % 2 == 0);
foreach (int item in result)
{
Console.Write(item);
Console.Write(",");
}
Console.WriteLine("\n");
//Get Multiplied value
var r = from n in numbers
select n * n;
Console.WriteLine("\nMULTIPLIED NUMBERS");
foreach (var item in r)
{
Console.Write(item);
Console.Write(",");
}
}
Output
As you could see the above code, most of them are pretty straight forward except even number. Hence lets take that for detailed demonstration.
Even Number
Here is the code for even number
IEnumerable result= numbers.Where(x => x % 2 == 0).Select(x => x);
foreach (int item in result)
{
Console.Write(item);
Console.Write(",");
}
As you can see, I have first used a Where extension method and used lambda expression to in such a way that, select only value which returns 0 on performing division with number 2 and then I am selecting that number.
Question
Do you think we still need the Select extension method?
The answer is actually
NO, we can write the code like this
IEnumerable result= numbers.Where(x => x % 2 == 0)
The above code will produce the same output as with select.
I hope this article gave some idea on how to work with Numbers in LINQ.
Thanks,
Karthik KK