2017-03-29 5 views
1

各国の月合計を計算しています。国別にデータをグループ化することができましたが、エラーが発生します2辞書を作成してそれを2回グループ化する方法

同じキーの項目が既に追加されています。

var totalPerMonth = data.AsEnumerable() 
     .Select(x => new 
     { 
      Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"), 
      Country = x.ItemArray[1], 
      Revenue = x.ItemArray[2] 
     }) 
     .GroupBy(x => x.Country) 
     .ToDictionary(x => x.Key, x => x.ToDictionary(p => p.Date,////this is not unique/// p => Convert.ToDouble(p.Revenue))); 

それが日付キーを一意にするためにどのようにグループ:内部ディクショナリに毎月の合計を置くしようとしている

答えて

1

ToLookupの代わりにToDictionaryを使用すると、同じ日付に複数の値を入力できます。

それともあなただけのユニークな日付を取得するために、グループ化を使用することができます(あなたは、各月の合計を計算するとしますので、各日付グループdgの収益のSumを使用):(

var totalPerMonth = data.AsEnumerable() 
    .Select(x => new { 
     Date = Convert.ToDateTime(x.ItemArray[0]).ToString("yyyy-MM"), 
     Country = x.ItemArray[1], 
     Revenue = Convert.ToDouble(x.ItemArray[2]) // convert here 
    }) 
    .GroupBy(x => x.Country) 
    .ToDictionary(
     g => g.Key, 
     g => g.GroupBy(x => x.Date).ToDictionary(dg => dg.Key, dg => dg.Sum(x => x.Revenue)) 
    ); 
+0

するvar totalPerMonth = data.AsEnumerable ) .Select( X => 新しい{ 日= Convert.ToDateTime(x.ItemArray [0])。ToStringメソッド( "YYYY-MM")、 国= x.ItemArray [1]、 収入= x.ItemArray [2] })。GroupBy (x => x.Country).ToDictionary(x => x.Key、x => x.GroupBy(p => p.Date).ToDictionary(p => p.Key、p => p.Sum(t) => Convert.ToDouble(t.Revenue)))); – Ekaterina

+1

このように、アイデアのおかげで! – Ekaterina

+0

@Ekaterinaうん、ちょうどクエリ変数名について考えた後に更新していた –

関連する問題