Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct year-months with Linq (to entities)

I have an entity set of Publications with a ReleaseDate property. I would like to get a List of all distinct year-&-month combos from this set for the purpose of creating a pagination widget.

Preferably, I'd like a list of DateTime values with the day as 1 for each distinct year-month from my publications set:

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

How can I finish this linq-to-entities query?

like image 283
Faust Avatar asked Nov 04 '11 14:11

Faust


2 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

The intermediate step to project into an anonymous type is necessary because you cannot directly project into a DateTime (constructors with parameters are not supported in projections in LINQ to Entities and the Year and Month properties of DateTime are readonly, so you can't set them with initializer syntax (new DateTime { Year = p.ReleaseDate.Year, ... } is not possible)).

like image 76
Slauma Avatar answered Sep 19 '22 03:09

Slauma


Try the following query:

(from p in publications
 select new DateTime(p.ReleaseDate.Year, p.ReleaseDate.Month, 1)).Distinct();
like image 24
Wouter de Kort Avatar answered Sep 21 '22 03:09

Wouter de Kort