排序C#中的对象列表 [英] Sorting a List of objects in C#

查看:73
本文介绍了排序C#中的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class CarSpecs
{
  public String CarName { get; set; }

  public String CarMaker { get; set; }

  public DateTime CreationDate { get; set; }
}

这是一个列表,我试图找出一种有效的方法排序这个列表List CarList,包含6(或任何整数)Cars,由Car Make Date。我打算做泡泡排序,但会工作吗?任何帮助?

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?

感谢

推荐答案

List< T> 类使得这一点变得轻而易举,因为它包含 排序方法。 (它使用QuickSort算法,而不是Bubble Sort,这通常更好)。更好的是,它有一个重载,它需要一个比较< T> 参数,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆