在C#中对对象列表进行排序

37 c# sorting class list

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

  public String CarMaker { get; set; }

  public DateTime CreationDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是一个列表,我试图找出一种有效的方法来排序列表CarList,包含汽车生产日期的6(或任何整数)汽车.我打算做冒泡排序,但那会有用吗?任何帮助?

谢谢

Nol*_*rin 86

这个List<T>类对你来说很简单,因为它包含一个Sort方法.(它使用QuickSort算法,而不是冒泡排序,无论如何通常都更好.)更好的是,它有一个带Comparison<T>参数的重载,这意味着你可以传递一个lambda表达式并使事情变得非常简单.

试试这个:

CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));
Run Code Online (Sandbox Code Playgroud)


Arj*_*nbu 58

您可以使用LINQ:

listOfCars.OrderBy(x => x.CreationDate);
Run Code Online (Sandbox Code Playgroud)

编辑:使用这种方法,它很容易添加更多排序列:

listOfCars.OrderBy(x => x.CreationDate).ThenBy(x => x.Make).ThenBy(x => x.Whatever);
Run Code Online (Sandbox Code Playgroud)

  • 是的,这也可以完成这项工作.然而,它会比使用List.Sort更糟糕的性能,因为它基于LINQ(即IEnumerable <T>对象),尽管从最初的问题看起来并不是什么大问题.唯一真正的区别是它返回一个新对象(然后你必须使用`ToList()`转换为一个列表),而List.Sort在当前实例上执行排序. (4认同)

And*_*ndy 17

最好的方法是实现IComparableIComparable<T>,然后调用List<T>.Sort().这将为您排序所有艰苦的工作.

  • 一个代码示例虽然很好. (3认同)
  • +1来对抗别人做的无意义的-1.这个建议没有错. (2认同)

Pet*_*ter 14

另一种选择是使用自定义比较器:

using System;
using System.Collections.Generic;
using System.Text;

namespace Yournamespace
{
   class CarNameComparer : IComparer<Car>
   {
      #region IComparer<Car> Members

      public int Compare(Car car1, Car car2)
      {
         int returnValue = 1;
         if (car1 != null && car2 == null)
         {
            returnValue = 0;
         }
         else if (car1 == null && car2 != null)
         {
            returnValue = 0;
         }
         else if (car1 != null && car2 != null)
         {
            if (car1.CreationDate.Equals(car2.CreationDate))
            {
               returnValue = car1.Name.CompareTo(car2.Name);
            }
            else
            {
               returnValue = car2.CreationDate.CompareTo(car1.CreationDate);
            }
         }
         return returnValue;
      }

      #endregion
   }
}
Run Code Online (Sandbox Code Playgroud)

你这样称呼:

yourCarlist.Sort(new CarNameComparer());
Run Code Online (Sandbox Code Playgroud)

注意:我没有编译此代码,因此您可能必须删除拼写错误

编辑:对其进行修改,以便比较器按照相关要求对创建日期进行比较.


Egi*_*sen 6

我只想在List.Sort方法中使用build.它使用QuickSort算法,该算法平均以O(n log n)运行.

此代码应该适合您,我将您的属性更改为自动属性,并定义一个静态CompareCarSpecs方法,该方法只使用现有的DateTime.CompareTo方法.

class Program
{
    static void Main(string[] args)
    {
        List<CarSpecs> cars = new List<CarSpecs>();
        cars.Sort(CarSpecs.CompareCarSpecs);
    }
}

public class CarSpecs
{
    public string CarName { get; set; }
    public string CarMaker { get; set; }
    public DateTime CreationDate { get; set; }

    public static int CompareCarSpecs(CarSpecs x, CarSpecs y)
    {
        return x.CreationDate.CompareTo(y.CreationDate);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.