Distinctive months with Linq (for legal entities)

I have a set of Publications objects with the ReleaseDate property. I would like to get a list of all the individual annual and ambitious combos from this set in order to create a pagination widget.

Preferably, I would like the list of DateTime values ​​from day to be 1 for each reporting year from my publication set:

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

How can I end this linq-to-entity query?

+5
source share
5 answers
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

, DateTime ( LINQ to Entities Year Month DateTime readonly, (new DateTime { Year = p.ReleaseDate.Year, ... } )).

+12

:

(from p in publications
 select new DateTime(p.ReleaseDate.Year, p.ReleaseDate.Month, 1)).Distinct();
+2

Using the By group:

(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));
+1
source
var DistinctYearMonths = (from p in context.Publications
                          select new DateTime(p.ReleaseDate.Year,
                                              p.ReleaseDate.Month,
                                              1)).Distinct();
0
source
var DistinctYearMonths = context.Publications
    .Select(x => new DateTime(x.ReleaseDate.Year, x.ReleaseDate.Month, 1))
    .Distinct()
    .ToList()

I like chained linq methods much better than long form. They are much easier to read IMO.

0
source

All Articles