1

I'm learning about .csv file handling in C#.

Suppose I have a .csv file that contains the following data.

industryName,value,currency 

Engineering,1000,USD

Agriculture,2000,EUR

Engineering,3000,LKR

Agriculture,4000,USD

I want to get the summation of the column named value if the currency is USD only. For example, summation in this dataset will be 5000(1000+4000)

It is highly appreciated if someone can give a code snippet with the answer.

Kavindu Tharaka
  • 231
  • 2
  • 7
  • 1
    Nobody can give it to you. You can try it on your own, and then someone can help you once you get stuck. – Josip Juros Mar 14 '22 at 13:21
  • 1
    You may look at NuGet package [CSVHelper](https://www.nuget.org/packages/CsvHelper/) or you can just read it as text using [File.ReadAllLines](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=net-6.0) – Tu deschizi eu inchid Mar 14 '22 at 13:31

1 Answers1

2

Read the data into simple objects

public class IndustryValue
{
    public string IndustryName { get; set; }
    public int Value { get; set; }
    public string Currency { get; set; }
}

IEnumerable<IndustryValue> GetIndustryValues(/* whatever parmas you need to get the csv data*/)
{
    List<IndustryValue> industries = //get you industries from csv

    return industries;
}

Then use simple linq to the sum

var byIndustry = industryValues.Where(i => i.Industry.Equals("Agriculture")).Sum(i => i.Value);

var byCurrency = industryValues.Where(i => i.Currency.Equals("USD")).Sum(i => i.Value);

var byIndustryAndCurrency = industryValues.Where(i => i.Industry.Equals("Agriculture") && i.Currency.Equals("USD")).Sum(i => i.Value);
    
Barry O'Kane
  • 1,189
  • 7
  • 12