1

I cant for the life of me figure out why this List will not sort properly. Can someone point out what I am doing wrong?

List<WNBlogPost> posts = new List<WNBlogPost>();

IEnumerable<WNBlogPost> orderedPosts = (
    from p in posts
    select p
).OrderByDescending(c => c.ID);

foreach (WNBlogPost post in orderedPosts) {
    //output post to page
}

I am adding items to the posts list in loop, but the order they are added to the list is the same order they appear in after I add OrderByDescending().

Any idea what I am doing wrong?

5
  • 10
    Why would you use that syntax instead of posts.OrderByDescending(c => c.ID)? Commented Apr 19, 2012 at 18:04
  • Firstly what type is WNBlogPost.ID? Secondly you wouldn't happen to be looking at posts instead of orderedPosts by any chance? Commented Apr 19, 2012 at 18:07
  • WNBlogPost.ID is an int field Commented Apr 19, 2012 at 18:10
  • @Duane: perhaps a silly question, but what does simply writing out post.ID look like? Commented Apr 19, 2012 at 18:15
  • so it turns out i am a complete idiot. the code was working properly, but a user control feeding my data was set to return the first 50 posts instead of the last 50. The sorting was working correctly, i was just sorting the wrong set. Thanks for all the help everyone Commented Apr 19, 2012 at 18:29

1 Answer 1

12

LINQ queries (without external effort) do not introduce side-effects into the collections they operate on. Therefore, OrderByDescending only presents a sorted view of posts which you can access via orderedPosts.

// hat-tip: @JimSchubert
foreach (var post in orderedPosts)
{
    Frob(post); // these will be frobbed in descending order
}

If you would like to sort the actual list itself, you should use List<T>.Sort:

// utilize the Comparison<T> overload of List<T>.Sort to perform a
// descending sort based on the post ID
posts.Sort((post1, post2) => -post1.ID.CompareTo(post2.ID));
Sign up to request clarification or add additional context in comments.

1 Comment

Also, you then have to enumerate over orderedPosts for it to be useful :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.