对Linq查询进行排序

时间:2012-04-19 18:02:44

标签: c# linq

我不能为我的生活弄清楚为什么这个List不能正确排序。有人可以指出我做错了吗?

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
}

我在循环中将项目添加到帖子列表,但是它们添加到列表中的顺序与我在添加OrderByDescending()后出现的顺序相同。

知道我做错了吗?

1 个答案:

答案 0 :(得分:12)

LINQ查询(无需外部努力)不会将副作用引入其操作的集合中。因此,OrderByDescending仅显示posts的已排序视图,您可以通过orderedPosts访问该文件。

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

如果您想对实际列表进行排序,则应使用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));