10

私は次のクラス構造を持っています:

public class PriceLog
{
   public DateTime LogDateTime {get; set;}
   public int Price {get; set;}
}

List< PriceLog >の場合、Linq クエリで、以下に示すデータと同等の出力を生成する必要があります。

LogDateTime | AVG(価格)
2012年1月 | 2000
2012 年 2 月 | 3000

簡単に言うと、その年の各月の平均価格を計算したいのです。
注: LogDateTime プロパティは次のようにフォーマットする必要があります。LogDateTime.ToString("MMM yyyy")

次のことを試しましたが、目的の結果が得られるかどうかはわかりません。

var result = from priceLog in PriceLogList
                         group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
                         select new PriceLog { GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)};
4

4 に答える 4

21

これにより、日付文字列と平均価格の 2 つのプロパティを含む一連の匿名オブジェクトが得られます。

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

PriceLog オブジェクトのリストを取得する必要がある場合:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };
于 2013-01-19T20:03:44.700 に答える
3
    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }
于 2013-01-19T19:49:49.753 に答える
3

次のように試してみてください。

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };
于 2013-01-19T20:02:30.367 に答える
1
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

Price フィールドが int で、Average メソッドが double を返すため、int に変換しました。

于 2013-01-19T20:08:44.037 に答える