C# Linq的不同年度月份(至实体)
我有一个具有ReleaseDate属性的出版物实体集。为了创建分页小部件,我想从这个集合中获得所有不同的年和月组合的列表 最好是,我希望从我的出版物集中,为每个不同的年-月列出日期时间值,日期为1:C# Linq的不同年度月份(至实体),c#,linq,entity-framework,C#,Linq,Entity Framework,我有一个具有ReleaseDate属性的出版物实体集。为了创建分页小部件,我想从这个集合中获得所有不同的年和月组合的列表 最好是,我希望从我的出版物集中,为每个不同的年-月列出日期时间值,日期为1: IEnumerable<DateTime> DistinctYearMonths = from p in context.Publications. .... ? IEnumerable DistinctYearMonths=来自context.Publications中的p? 如
IEnumerable<DateTime> DistinctYearMonths = from p in context.Publications. .... ?
IEnumerable DistinctYearMonths=来自context.Publications中的p?
如何完成此linq到实体查询?请尝试以下查询:
(from p in publications
select new DateTime(p.ReleaseDate.Year, p.ReleaseDate.Month, 1)).Distinct();
使用分组方式:
(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));
比起长格式,我更喜欢链式linq方法。在我看来,它们更容易阅读。IEnumerable DistinctYearMonths=context.Publications
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
.Select(p=>new{p.ReleaseDate.Year,p.ReleaseDate.Month})
.Distinct()
.ToList()//执行查询
.选择(x=>newdatetime(x.Year,x.Month,1));//复制匿名对象
//在内存中输入日期时间
投影到匿名类型的中间步骤是必要的,因为您不能直接投影到
DateTime
(在LINQ到实体的投影中不支持带参数的构造函数,DateTime
的Year
和Month
属性是只读的,因此不能使用初始值设定项语法设置它们(newdatetime{Year=p.ReleaseDate.Year,…}
不可能)。hmm.我得到了“System.NotSupportedException:LINQ to实体中仅支持无参数构造函数和初始值设定项。“当我把这个正确地放到LinqPad中时——有什么想法吗?@Faust的意思是,ReleaseDate
没有在属性本身中初始化。初始化DateTime类型的POCO属性并按如下方式列出是一个很好的做法:public virtual List Followers{get;set;}=new List()
和public virtual DateTime CreatedDate{get;set;}=DateTime.UtcNow;
您赢了。和+1作为一个很好的解释——这里的所有其他答案都类似于“System.NotSupportedException:LINQ to Entities只支持无参数构造函数和初始值设定项。”
var DistinctYearMonths = context.Publications
.Select(x => new DateTime(x.ReleaseDate.Year, x.ReleaseDate.Month, 1))
.Distinct()
.ToList()
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