不同的一年个月使用LINQ(实体) [英] Distinct year-months with Linq (to entities)

查看:110
本文介绍了不同的一年个月使用LINQ(实体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有出版物用RELEASEDATE属性的实体集。我想获得所有不同年 - &放的名单;从这组创建分页控件的目的个月的连续技



最好的,我想日期时间值与天为1为每个不同的年月份,从我的出版物设置列表:

 的IEnumerable< DateTime的>从对DistinctYearMonths =在context.Publications。 ....? 



我要如何完成这个LINQ到实体查询?


< DIV CLASS =h2_lin>解决方案

 的IEnumerable<&日期时间GT; DistinctYearMonths = context.Publications 
。选择(P =>新建{p.ReleaseDate.Year,p.ReleaseDate.Month})
.Distinct()
.ToList()// excutes查询
。选择(X =>新建日期时间(x.Year,x.Month,1)); //复制匿名对象
//进入日期时间内存

的中间步骤,伸入匿名类型是必要的,因为你不能直接伸入的DateTime (带参数的构造函数在LINQ预测是不支持实体和年度属性的DateTime 是只读的,所以你不能初始化语法设置它们( 新的datetime {=年p.ReleaseDate.Year,...} 是不可能的))。


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?

解决方案

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)).

这篇关于不同的一年个月使用LINQ(实体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆