C# 关于类聚合关系的linq orderby帮助

C# 关于类聚合关系的linq orderby帮助,c#,linq-to-objects,C#,Linq To Objects,我有点困惑,需要一些帮助。上这两门课 public class Comment { public string Message {get; set;} public DateTime Created {get; set;} } public class Post { public int PostId {get; set;} public string Content {get; set;} public IList<Comment> C

我有点困惑,需要一些帮助。上这两门课

public class Comment
{
     public string Message {get; set;}
     public DateTime Created {get; set;}
}

public class Post
{
    public int PostId {get; set;}
    public string Content {get; set;}
    public IList<Comment> Comments {get; set;}
}
但是orderby语句似乎不起作用!它只是以默认的排序顺序返回我的列表。有什么建议可以让我这样做吗??? 提前谢谢

按哪个评论日期排序?第一个?最后?你可以试试:

orderby p.Comments.Max(x=>x.Created)
比如说

另外-您的
单列
表明您希望正好一行,在这种情况下,排序它没有多大意义。你的意思是说
First()


或者您的意思是要对
注释进行排序
?在这种情况下,首先获取
Post

Post post = ...
现在。。。排序
注释
有点棘手,因为您的
IList
——如果您不介意它有点低效,这很简单:

post.Comments = post.Comments.OrderBy(x=>x.Created).ToList();
当然,如果
注释
列表
,您可以执行以下操作:

post.Comments.Sort((x, y) => (x.Created.CompareTo(y.Created)));
您还可以使用以下技巧创建表单的扩展方法:

post.Comments.Sort(x=>x.Created);
i、 e

公共静态无效排序(
此列表来源:,
Func选择器)
{
var comparer=comparer.Default;
Sort((x,y)=>comparer.Compare(选择器(x),选择器(y));
}

您的orderby投影正在返回一个
IEnumerable
——听起来不太可能是您想要的

一篇文章有很多评论-你想把哪一条作为使用创建日期进行订购的评论?我猜是第一个:

var query = from p in _repository.GetPosts()
                    where p.PostId == id
                    orderby {
                        Comment comment = p.Comments.FirstOrDefault();
                        return comment == null ? DateTime.MinValue : comment.Created;
                    }
                    select p;

这将在IEnumerable集合中返回,该集合不是可比较的值:

p.Comments.Select(x => x.Created)
请尝试以下方法:

p.Comments.Max(x => x.Created)

返回最新评论的日期

如果要对结果评论列表进行排序,可以在获取文章后执行以下操作:

p.Comments = p.Comments.OrderBy(x => x.Created).ToList();

.

问题在于,您试图按评论创建日期列表对帖子列表进行排序,而不是对评论列表进行排序

如果我没有看错你的问题,我假设你想把这篇文章拿出来,然后在那篇文章里排序评论。请尝试执行以下操作:

var query = from p in _repository.GetPosts()
            where p.PostId == id
            orderby p.Comments.Select(x => x.Created)
            select p;

var ret = query.Single();
ret.Comments = ret.Comments.OrderBy(x => x.Created).ToList();
return ret;
p.Comments = p.Comments.OrderBy(x => x.Created).ToList();
var query = from p in _repository.GetPosts()
            where p.PostId == id
            orderby p.Comments.Select(x => x.Created)
            select p;

var ret = query.Single();
ret.Comments = ret.Comments.OrderBy(x => x.Created).ToList();
return ret;