1

日時フィールドの月ごとにグループ化されたオブジェクトの数を取得する必要があるシナリオがあります。

私はそこへの道のりの一部を得る次の投稿を見つけました...

Linq: 年月ごとにグループ化し、空の月を管理する

...しかし、今日の日付から過去 12 か月分と、各月のオブジェクトの数をリストする必要があります。ここで苦労しています。

同様の問題/解決策を持つ他のいくつかの投稿を見てきましたが、カウントが 0 の任意の月のレコードを作成する必要があるため、上記の投稿を選択しました。

これについて何か助けてくれてありがとう。

編集

OK、エニグマティビティのおかげでもう少し進めました (時間を割いてくれてありがとう!):

var news = from s in db.NewsItems
                   where s.SubmittedDate > first
                   select new 
                   {
                       Date = s.SubmittedDate,
                       Title = s.Title,
                   };

var grouping = from g in news.AsEnumerable()
                       select new NewsCountCollection
                       (
                           g.Date,
                           g.Title
                       );

var lookup = grouping.ToLookup(x => x.Month, x => x.Title);

var counts = from n in Enumerable.Range(-11, 12)
                    let Month = last.AddMonths(n)
                    select new
                    {
                        Month,
                        Count = lookup[Month].Count(),
                    };

var countList = from c in counts.AsEnumerable()
                        select new NewsCountMonthList
                        (
                            c.Month.ToString("MMMM"),
                            c.Count
                        );

...そして以下

public class NewsCountCollection
{
    public DateTime Month { get; set; }
    public string Title { get; set; }

    public NewsCountCollection(DateTime date, string title)
    {
        this.Month = new DateTime(date.Year, date.Month, 1);
        this.Title = title;
    }

}

public class NewsCountMonthList
{
    public string Month { get; set; }
    public int Count { get; set; }

    public NewsCountMonthList(string month, int count)
    {
        this.Month = month;
        this.Count = count;
    }
}

...非常に非効率に思えますが...これよりも良い方法があるに違いないと思わずにはいられません。私は正しい軌道に乗っていますか?

4

1 に答える 1

2

これでうまくいくはずです:

var now = DateTime.Now;
var last = new DateTime(now.Year, now.Month, 1);
var first = last.AddMonths(-12);

var query =
    from s in somethings
    where s.DateTimeField >= first
    where s.DateTimeField < last
    select new
    {
        Month = new DateTime(s.DateTimeField.Year, s.DateTimeField.Month, 1),
        Something = s,
    };

var lookup = query.ToLookup(x => x.Month, x => x.Something);

var counts =
    from n in Enumerable.Range(-12, 12)
    let Month = last.AddMonths(n)
    select new
    {
        Month,
        Count = lookup[Month].Count(),
    };

少しいじる必要があるかもしれませんが、構造は健全でなければなりません。

于 2012-06-26T11:11:23.847 に答える