1

次のようなデータを格納するモデル「フルーツ」があります。

date         fruit_code   count
2013/09/30   apple        10
2013/09/30   pear         5
2013/10/01   apple        1
2013/10/01   pear         2
2013/10/02   apple        5

私が望むのは、各月の各果物の合計を表示することだけです。出力は次のようになります。

date         no_of_apple   no_of_pear
2013/09      10            5
2013/10      6             2

私はこのようにlinqを構築しようとしましたが、立ち往生しました:

from o in fruit
let keys = new 
{ 
   date = o.date.ToString("yyyy/MM"),
   fruit = o.fruit_code
}
group o by keys into grp
select new 
{
   date = grp.Key.date,
   no_of_apple = // I got stucked here, wondering how to 
   no_of_pear = // calculate the conditional sum
}

前もって感謝します。

4

5 に答える 5

5

これを試して:

var result = fruit.GroupBy(i => i.date)
            .Select(i => new
            {
                date = i.Key,
                no_of_apple = i.Where(j => j.fruit_code == "apple").Sum(k => k.count),
                no_of_pear = i.Where(j => j.fruit_code == "pear").Sum(k => k.count)
            });
于 2013-10-13T08:58:59.980 に答える
0

月ごとにグループ化し、結果の選択でリンゴ/ナシを数えることができます。

var v = from o in fruit
  group o by new {o.date.Year, o.date.Month} into grp
  select new 
  {
    date = grp.Key,
    no_of_apples = 
      (from a in grp where a.fruit_code == "apple" select a.count).Sum(),
    no_of_pears = 
      (from p in grp where p.fruit_code == "pear" select p.count).Sum(),
  };        
于 2013-10-13T08:53:09.233 に答える
0

から派生したAppleとの 2 つのクラスがあり、それらにプロパティが含まれているとします。PearFruitCount

from o in fruit
let month = o.date.ToString("yyyy/MM") 
group o by month into grp
select new 
{
    date = grp.Key,
    no_of_apple = grp.OfType<Apple>.Sum(apple=>apple.Count),
    no_of_pear = grp.OfType<Pear>.Sum(pear=>pear.Count),
}
于 2013-10-13T08:29:14.110 に答える