C# Linq OrderBy聚合日期
我想按最后评论的日期或帖子的日期订购一份帖子列表 以下是课程:C# Linq OrderBy聚合日期,c#,.net,linq,C#,.net,Linq,我想按最后评论的日期或帖子的日期订购一份帖子列表 以下是课程: 公共类职位 { 公共int Id{get;set;} 公共字符串文本{get;set;} public System.DateTime DatePosted{get;set;} 公共ICollection注释{get;set;} } 公共部分类注释 { 公共int Id{get;set;} 公共int PostId{get;set;} 公共字符串文本{get;set;} public System.DateTime Date
公共类职位
{
公共int Id{get;set;}
公共字符串文本{get;set;}
public System.DateTime DatePosted{get;set;}
公共ICollection注释{get;set;}
}
公共部分类注释
{
公共int Id{get;set;}
公共int PostId{get;set;}
公共字符串文本{get;set;}
public System.DateTime DateCommented{get;set;}
}
理想的代码(whitch甚至不编译)是:
IEnumerable posts=MVPMetroEntities.posts
.OrderByDescending(p=>
p、 DatePosted | | p.Comments.Max(c=>c.DateCommented));
有什么想法吗?谢谢我猜您正在寻找
,然后通过降序
:
IEnumerable<Post> posts = MVPMetroEntities.Posts
.OrderByDescending(p => p.DatePosted)
.ThenByDescending(p => p.Comments.Max(c => c.DateCommented));
IEnumerable posts=MVPMetroEntities.posts
.OrderByDescending(p=>p.DatePosted)
.ThenByDescending(p=>p.Comments.Max(c=>c.DateCommented));
我不太明白你的意图,但是这个怎么样
MVPMetroEntities.Posts
.OrderByDescending(p => Recent(p.DatePosted, p.Comments.Max(c => c.DateCommented)));
通过使用像这样的辅助方法/扩展方法
public DateTime Recent(DateTime dt1, DateTime dt2)
{
return dt1 > dt2 ? dt1 : dt2;
}
注意:如果您使用的是任何ORM,如Linq to sql,则helper可能不起作用。我找到了答案,在OrderByDescending中使用了三元运算符。谢谢:)
var posts = MVPMetroEntities.Posts
.Select(p => new {
Date = p.Comments.Any()
? p.Comments.OrderByDescending(c => c.DateCommented).First().Date
: p.DatePosted,
Post = p
}
.OrderByDescending(x => x.Date);
你看到这个问题了吗
p.DatePosted
是不可为空的DateTime
;通过p.DatePosted | | p.Comments.Max(…)
,您想做什么?如果你解释一下你想要达到的目标,我们可能会提供帮助。按“最后评论日期或发布日期”(强调我的)排序意味着什么?这是什么意思?把它放在上下文中:如果我说“按身高或鞋号排列这张名单”——这是什么意思?结果会怎样?很抱歉造成这种混乱。我的意思是:如果没有评论,则按日期发布,或者按最后一条评论的日期发布。我相信他想按最近的评论发布,如果没有评论,则按发布日期发布。只有当OrderByDescending具有相同的时间戳时,InByDescending才有效,对吗?@Raph:是的,类似于sql查询,您可以通过逗号分隔多个ORDER BY
。感谢三元运算符的想法,我将直接在“OrderBy”中使用它
var posts = MVPMetroEntities.Posts
.Select(p => new {
Date = p.Comments.Any()
? p.Comments.OrderByDescending(c => c.DateCommented).First().Date
: p.DatePosted,
Post = p
}
.OrderByDescending(x => x.Date);
MVPMetroEntities.Posts
.OrderByDescending(
e => e.Comments.Any() ? e.Comments.Max(f => f.DateCommented) : e.DatePosted)