Finding the average value in a sequence with LINQ C#
August 1, 2014 2 Comments
The LINQ Average operator can be applied to sequences of numeric types. In its simplest form it returns an average value of type double:
List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 }; double average = integers.Average();
…which gives about 552.14.
The operator can be applied to sequences of custom objects using a selector function:
public class Singer { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int BirthYear { get; set; } } IEnumerable<Singer> singers = new List<Singer>() { new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964} , new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954} , new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954} , new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950} , new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964} }; double averageBirthYear = singers.Average(s => s.BirthYear);
…which is of course not too meaningful, but you get the idea.
View the list of posts on LINQ here.
Hi Andras!
myrecatlist contains following data table/contents
BookDate(YYYYMMDD) AccountNumber Amount Type
20140901 123456 10.00 020
20140910 123456 15.00 020
20141007 123456 7.00 020
20141020 123456 7.00 020
20141103 123456 15.00 020
20140915 222222 10.00 020
20141010 222222 10.00 020
20141015 222222 10.00 020
20141110 222222 10.00 020
and results I would like to see are Average BookDates and Average Amounts for same account
so it would look like this:
For AccountNumber 123456 Average for all given months is 1.67 because for month 201409 count=2, for month 201410 count=2 and for 201411 count=1, so average = (2+2+1)/3 = 1.67; and on the Amount then would be Average=18 because for month 201409 sum=25, for month 201410 sum=14 and for month 201411 sum=15, so Average = (25+14+15)/3 = 18.
For AccountNumber 222222 Average for all given months is 1.33 because for month 201409 count=1, for month 201410 count=2 and for 201411 count=1, so average=(1+2+1)/3 = 1.33; and on the Amount then would be Average=13.33 because for month 201409 sum=10, for month 201410 sum=20, and for month 201411 sum=10, so Average = (10+20+10)/3 = 13.33.
Do I have to do something like the following? I really have doubt in this
var cat20 = (
from myl20 in myrecatlist
where myl20.TRANSACTIONCODE == “020”
group new {myl20.CUSTOMERACCOUNTNUMBER, myl20.BOOKDATE.Substring(0, 6), myl20.LCYAMOUNT} by myl20.TRANSACTIONCODE into g20
select new { new20CUSTACCTNUM = g20.Key, new20AvgLcyAmount = g20.Average(myl20 => myl20.LCYAMOUNT) });
Int32 thecounter = cat20.Count();
Hi Humberto, does your LINQ function give the expected results that you calculated? //Andras