2011-11-04 12 views
5

私は、ReleaseDateプロパティを持つパブリケーションのエンティティセットを持っています。私は、ページネーションウィジェットを作成する目的で、このセットからすべての別の年 - & - 月コンボのリストを取得したいと考えています。Linqとの別個の年月(エンティティへ)

好ましくは、私が設定自分の出版物からそれぞれ異なった年月のために1として日でのDateTime値のリストが欲しい:

IEnumerable<DateTime> DistinctYearMonths = from p in context.Publications. .... ? 

どのように私はこのLINQツーエンティティクエリを終えることができますか?私は長い形式よりもはるかに優れチェーンLINQのメソッドを好き

(from i in context.Publications 
group i by new { i.ReleaseDate.Year, i.ReleaseDate.Month } into g 
select g.Key).ToList().Select(i => new DateTime(i.Year, i.Month, 1)); 

答えて

12
IEnumerable<DateTime> DistinctYearMonths = context.Publications 
    .Select(p => new { p.ReleaseDate.Year, p.ReleaseDate.Month }) 
    .Distinct() 
    .ToList() // excutes query 
    .Select(x => new DateTime(x.Year, x.Month, 1)); // copy anonymous objects 
                // into DateTime in memory 

中間ステップが必要である(パラメータを持つコンストラクタがエンティティにLINQに凸でサポートされていないとDateTimeYearMonthプロパティは読み取り専用であり、初期化の構文でそれらを設定することはできません(new DateTime { Year = p.ReleaseDate.Year, ... }は不可能です))。

+0

あなたが勝ちます。 +良い説明のための+1 - 他のすべての答えは "System.NotSupportedExceptionを生成するのに似ています:LINQ to Entitiesでパラメータなしのコンストラクタと初期化子のみがサポートされています。" – Faust

2

は、次のクエリを試してみてください。 IMOを読むのがはるかに簡単です。あなたが直接DateTimeに突出することができないので、匿名型に投影する

+0

Hmmm。私は "System.NotSupportedException:LINQ to Entitiesでパラメータなしのコンストラクタと初期化子だけがサポートされています。"私はLinqPadにこの権利を置くとき - それについてのいかなる考え? – Faust

+0

FWIW LinqPadでうまく動作します –

+0

@Please 'ReleaseDate'がプロパティ自体で初期化されていなかったことを意味します。 DateTime型のPOCOプロパティとリストのように、以下のように初期化するのは良い方法です。 'public virtual List Followers {get;セット; } = new List (); 'と' public仮想DateTime CreatedDate {get;セット; } = DateTime.UtcNow; ' – Korayem

0
var DistinctYearMonths = (from p in context.Publications 
          select new DateTime(p.ReleaseDate.Year, 
               p.ReleaseDate.Month, 
               1)).Distinct(); 
0
var DistinctYearMonths = context.Publications 
    .Select(x => new DateTime(x.ReleaseDate.Year, x.ReleaseDate.Month, 1)) 
    .Distinct() 
    .ToList() 

:することにより、グループを使用して

(from p in publications 
select new DateTime(p.ReleaseDate.Year, p.ReleaseDate.Month, 1)).Distinct(); 
関連する問題