Estevao Santiago Estevao Santiago - 8 months ago 60
C# Question

Use LINQ to group by one field, sum based on group AND store on Dictionary

I am having a hard time to achieve a result likely because I'm misunderstanding sintax. Here the case:

I have a class that outputs a list. In this list there are two fields that I want specifically. they are ItemID (string) and TotalNet (string). There are other fields but I don't need to work with them at this point, but I do later at code.

The ItemID is the identifier of an Item, it is not unique in the list, so I must group it into one and account how many times this item appears. I achieved that with the following:

Dictionary<string, int> dstLoops = list.Select(l => l.ItemID).ToList()
.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());

So I get my dictionary with the ItemID, now unique, with the total times that Item appears on my list.

The part that I am struggling to achieve is to sum the TotalNet of all the times the ItemID appears on the list.

I managed to get that using this:

var APTotal = from i in list group i by i.ItemID into g select new
{ total = g.Key, totals = g.Sum(i =>Convert.ToDecimal(i.TotalAmountPaid)) };

The problem is, it is not a dictionary, and later in the code that will be a headache... well... not much but I would like to avoid it, so I tried:

Dictionary<string, decimal> liststotal = list.Select(l => l.ItemID).ToList().
GroupBy(x => x).ToDictionary(g => g.Key, g => g.Sum(Convert.ToDecimal(item.TotalAmountPaid)));

Unfortunately it returns me that I cannot convert decimal to System.Func

I have tried some other solutions from this forum and other places, but they usually don't add values to the dictionary.

I can accept two scenarios as a solution:

  1. Exactly what I requested above, where I will get a
    dictionary with all Items from my List grouped by
    ItemID and sum of their respective item.TotalNet;


Item1, 10
Item2, 15
Item2, 15


Item1, 10
Item2, 30

2. a var/decimal/whatever that returns me the TotalNet of the current
ItemID iteration (I can use a foreach/for later on the code to
achieve the result I am looking for). So to be clear, this TotalNet
must be the sum of all TotalNets with the same ItemID from my list
that I am iterating at the moment. Something like "I'am on ItemID 1,
go and sum all the TotalNet of ItemID 1 from List".

Honestly... I would like help with the first option, for the sake of learning, but a solution is appreciated whatever the means (sacrificing children in name of an old god to get my output will not be marked as a solution...and possibly down voted).


Would something like this work?

list.GroupBy(x => x.ItemID)
    .ToDictionary(x => x.Key, 
                  x => x.Sum(t => Convert.ToDecimal(t.TotalAmountPaid)));