C# 对Linq查询排序
我一辈子都搞不明白为什么这个列表不能正确排序。有人能指出我做错了什么吗C# 对Linq查询排序,c#,linq,C#,Linq,我一辈子都搞不明白为什么这个列表不能正确排序。有人能指出我做错了什么吗 List<WNBlogPost> posts = new List<WNBlogPost>(); IEnumerable<WNBlogPost> orderedPosts = ( from p in posts select p ).OrderByDescending(c => c.ID); foreach (WNBlogPost post in orderedP
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
}
List posts=newlist();
IEnumerable orderedPosts=(
从p到p
选择p
).OrderByDescending(c=>c.ID);
foreach(orderedPosts中的WNBlogPost){
//将文章输出到页面
}
我正在循环中将项目添加到posts列表中,但它们添加到列表中的顺序与添加OrderByDescending()后的顺序相同
知道我做错了什么吗?LINQ查询(无需外部努力)不会给它们操作的集合带来副作用。因此,OrderByDescending
仅显示posts
的排序视图,您可以通过orderedPosts
访问该视图
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
}
// hat-tip: @JimSchubert
foreach (var post in orderedPosts)
{
Frob(post); // these will be frobbed in descending order
}
如果要对实际列表本身进行排序,应使用:
//利用List.Sort的比较重载执行
//基于帖子ID的降序排序
posts.Sort((post1,post2)=>-post1.ID.CompareTo(post2.ID));
LINQ查询(无需外部努力)不会对其操作的集合产生副作用。因此,OrderByDescending
仅显示posts
的排序视图,您可以通过orderedPosts
访问该视图
// hat-tip: @JimSchubert
foreach (var post in orderedPosts)
{
Frob(post); // these will be frobbed in descending order
}
如果要对实际列表本身进行排序,应使用:
//利用List.Sort的比较重载执行
//基于帖子ID的降序排序
posts.Sort((post1,post2)=>-post1.ID.CompareTo(post2.ID));
为什么要使用该语法而不是posts.OrderByDescending(c=>c.ID)
?首先,WNLOGPOST.ID是什么类型?其次,您不会碰巧看到posts
而不是orderedPosts
,因为WNBlogPost.ID是一个intfield@Duane:也许这是个愚蠢的问题,但简单地写出post.ID
是什么样子的呢?结果证明我是个十足的白痴。代码工作正常,但是一个提供我的数据的用户控件被设置为返回前50篇文章,而不是最后50篇。排序正常,我只是选错了一组。谢谢大家的帮助为什么你要使用这种语法而不是posts.OrderByDescending(c=>c.ID)
?首先,WNBlogPost.ID是什么类型?其次,您不会碰巧看到posts
而不是orderedPosts
,因为WNBlogPost.ID是一个intfield@Duane:也许这是个愚蠢的问题,但简单地写出post.ID
是什么样子的呢?结果证明我是个十足的白痴。代码工作正常,但是一个提供我的数据的用户控件被设置为返回前50篇文章,而不是最后50篇。排序正常,我只是选错了一组。感谢所有人的帮助同样,你必须枚举超过orderedPosts
才能有用:DAlso,然后你必须枚举超过orderedPosts
才能有用:D