'Read a CSV and get the summation of a column based on a condition [duplicate]
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.
Solution 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barry O'Kane |
