0

I have a set of data which I'm retrieving through a Service Reference in C#. I'm trying to output that data into a CSV to summarize it for a report. Basically my final report should have 3 columns: Month | Store | Category | Cost, and so in my C# I'm retrieving the data for various sales lines from the data source and getting the Month, Store, Category and Cost for each line. I'm trying to use a data structure to sum up the cost for every line that has the same Month, Store and Category, and my intuition is to use a Dictionary:

var monthSales = new Dictionary<int, Dictionary<String, Dictionary<String, Decimal>>>();

So I get a line from my data source, get it's month, check if the month already exists in the dictionary, and if it doesn't, create a new entry for that month, and then in the next dictionary down I do the same for the Store, and then in the next dictionary down I do the same for the Category, and then I add the cost to the existing cost if there was an existing cost.

I just feel like I'm doing this the wrong way. Feels very long-winded.

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • What is *"data source"*? You should run query to get data you need directly, instead of getting all data and summing yourself. – Sinatr Sep 26 '17 at 09:05
  • @Sinatr unfortunately I don't know how to do that. The data source is Dynamics NAV, I'm using OData services through LINQ (I guess) to retrieve Sales Lines objects and Item objects. – TKoL Sep 26 '17 at 09:11
  • @Sinatr regardless, I would still like to know the correct data structure to summarize data in this way – TKoL Sep 26 '17 at 09:13
  • There is nothing bad in nested dictionary if you intend to access data using keys of different level. In your case however you need just one key to carry out calculation of sum. Perhaps `Tuple` will do. – Sinatr Sep 26 '17 at 09:18
  • @Sinatr of course, thank you! That's much simpler than what I was doing, I am a sucker for overthinking things. I haven't had much experience with C#, a tuple didn't even occur to me. – TKoL Sep 26 '17 at 09:20
  • @Sinatr if you post that comment as an answer I will mark it as correct. – TKoL Sep 26 '17 at 09:20
  • I have found a [duplicate](https://stackoverflow.com/q/9303859/1997232), rather close your question as duplicate to that one, it will come up in google for "nested dictionary alternative". – Sinatr Sep 26 '17 at 09:23

0 Answers0