简体   繁体   中英

Group List of Dictionaries by a Dictionary-key (C#)

I have a List of Dictionaries of type <String, String> . Dictionaries have the keys Revenue and Month.

A typical entry could be: Revenue = "10.080", Month = "1/2011"

I would like to get the revenue totals for each month, so I tried:

List<decimal> monthsTotals = data.Select(d => Convert.ToDecimal(d["Revenue"]))
    .GroupBy(d => d["Month"]).ToList<decimal>();

This does not work. The expression d["Month"]) is underlined.

Cannot apply indexing with [] to an expression of type 'decimal'.

The result of your Select is just the revenue. You're losing all the rest of that information. I suspect you want:

Dictionary<string, decimal> revenueByMonth =
    data.GroupBy(d => d["Month"], d => decimal.Parse(d["Revenue"]))
        .ToDictionary(group => group.Key, group => group.Sum());

The first step creates an IGrouping<string, decimal> - ie for each month, a sequence of revenue values.

The second step converts this into a Dictionary<string, decimal> by taking the group key (the month) as the dictionary key, and the sum of the group values as the dictionary value.

List<decimal> monthsTotals = data
  .GroupBy(d => d["Month"])
  .Select(d => d.Sum( r => Convert.ToDecimal(r["Revenue"])))
  .ToList<decimal>();

Turn those dictionaries into something useful.

public class RevenueData
{
   public decimal Revenue {get;set;}
   public string Month {get;set;}
}

List<RevenueData> result = data
  .Select(d => new RevenueData()
    { Revenue = Convert.ToDecimal(d["Revenue"]), Month = d["Month"] })
  .GroupBy(x => x.Month)
  .Select(g => new RevenueData()
    { Revenue = g.Sum(x => x.Revenue), Month = g.Key })
  .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM