I am getting a little confused and need some help please. Take these two classes
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;} }
I want to write a linq query which returns a single Post but ordered by the comment created date.
So i started off constructing my linq query as follows:
var query = from p in _repository.GetPosts() where p.PostId == id orderby p.Comments.Select(x => x.Created) select p; return query.Single();
But the orderby statement seem not to work! It just returns my list in the default sort order. Any suggestions on how i can make this work??? Thanks in advance!
Ordered by which comment date? the first? the last? You cuold try:
for example.
Also – your
Singlesuggests you expect exactly one row, in which case there isn’t much point sorting it. Do you meanFirst()?Or do you mean that you want to sort the
Comments? In which case, get thePostfirst;Now… sorting the
Commentsis a little tricky because of yourIList<T>– if you don’t mind it being a little inefficient, this is simple:Of course, if the
CommentswasList<T>, you could do:There are also tricks you can do to make an extension method of the form:
i.e.