Home > Blockchain >  How to find mean of field values based on the year in c# (Working with csv file in console applicati
How to find mean of field values based on the year in c# (Working with csv file in console applicati

Time:11-07

using (var csv = new CsvReader(reader, config))                 
{                    
    var records = csv.GetRecords<info>().ToList();                     
    return records;                 
}  

public class info 
{   
    public int value{get;set;}   
    public DateTime date{get;set;} 
}  

There is datetime field in info class.

I want to find the average of 'value' field on the basis of the year.

How to compare the year field with this date field?

I have no idea on how to do this.

CodePudding user response:

DateTime objects have a Year property. See: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.year?view=net-7.0 If you can use LINQ, you should be able to do something like:

records
.GroupBy(record => record.date.Year)
.Select(group => new {Year = group.Key, Avg = group.Average(rec => rec.value)})
  • Related