排序对象在C#列表 [英] Sorting a List of objects in C#
问题描述
public class CarSpecs
{
public String CarName { get; set; }
public String CarMaker { get; set; }
public DateTime CreationDate { get; set; }
}
这是一个列表,我试图找出一条有效途径这个排序列表列表卡洛斯,含6(或任意整数金额)汽车,由汽车制造日期。我打算做冒泡排序,而是将这项工作?任何帮助吗?
This is a list and I am trying to figure out an efficient way to sort this list List CarList, containing 6(or any integer amount) Cars, by the Car Make Date. I was going to do Bubble sort, but will that work? Any Help?
感谢
推荐答案
的列表< T>
类,这个平凡的你,因为它包含一个 排序
方法。 (它使用快速排序算法,不冒泡排序,通常是更好的反正。)更妙的是,它具有过载,需要一个比较< T>
的说法,这意味着你,可以通过lambda表达式,使事情确实很简单
The List<T>
class makes this trivial for you, since it contains a Sort
method. (It uses the QuickSort algorithm, not Bubble Sort, which is typically better anyway.) Even better, it has an overload that takes a Comparison<T>
argument, which means you can pass a lambda expression and make things very simple indeed.
试试这个:
CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));
这篇关于排序对象在C#列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!