用LINQ对类列表进行排序

编程入门 行业动态 更新时间:2024-10-23 06:21:52
本文介绍了用LINQ对类列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个List<MyClass>,我想按MyClass的DateTime CreateDate属性对其进行排序.

I have a List<MyClass> and I want to sort it by DateTime CreateDate attribute of MyClass.

使用LINQ可以吗?

谢谢

推荐答案

您可以按排序顺序枚举它:

You can enumerate it in sorted order:

IEnumerable<MyClass> result = list.OrderBy(element => element.CreateDate);

您还可以使用ToList()转换为新列表并重新分配给原始变量:

You can also use ToList() to convert to a new list and reassign to the original variable:

list = list.OrderBy(element => element.CreateDate).ToList();

这与对原始列表进行排序并不完全相同,因为如果仍然有人引用旧列表,他们将看不到新的排序.如果您实际上想对原始列表进行排序,则需要使用List<T>.Sort方法.

This isn't quite the same as sorting the original list because if anyone still has a reference to the old list they won't see the new ordering. If you actually want to sort the original list then you need to use the List<T>.Sort method.

更多推荐

用LINQ对类列表进行排序

本文发布于:2023-10-15 02:49:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493025.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!