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

时间:2022-09-10 20:29:39
public class CarSpecs
{
  public String CarName { get; set; }

  public String CarMaker { get; set; }

  public DateTime CreationDate { get; set; }
}

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?

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

Thanks

谢谢

10 个解决方案

#1


83  

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.

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

Try this:

尝试这个:

CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));

#2


56  

You could use LINQ:

您可以使用LINQ:

listOfCars.OrderBy(x => x.CreationDate);

EDIT: With this approach, its easy to add on more sort columns:

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

listOfCars.OrderBy(x => x.CreationDate).ThenBy(x => x.Make).ThenBy(x => x.Whatever);

#3


16  

The best approach is to implement either IComparable or IComparable<T>, and then call List<T>.Sort(). This will do all the hard work of sorting for you.

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

#4


14  

Another option would be to use a custom comparer:

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

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
   }
}

which you call like this:

你这样称呼:

yourCarlist.Sort(new CarNameComparer());

Note: I didn't compile this code so you might have to remove typo's

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

Edit: modified it so the comparer compares on creationdate as requested in question.

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

#5


6  

I would just use the build in List.Sort method. It uses the QuickSort algorithm which on average runs in O(n log n).

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

This code should work for you, I change your properties to auto-properties, and defined a static CompareCarSpecs method that just uses the already existing DateTime.CompareTo method.

此代码应该适合您,我将您的属性更改为自动属性,并定义一个静态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);
    }
}

Hope this helps.

希望这可以帮助。

#6


3  

Putting some of the pieces mentioned here together. This compiles and works in C# 4.x and VS2010. I tested with a WinForm. So add the method to the WinForm Main(). You will need the System.Linq and System.Generic.Collections assemblies at least.

将这里提到的一些部分放在一起。这在C#4.x和VS2010中编译和工作。我用WinForm测试过。所以将方法添加到WinForm Main()。您至少需要System.Linq和System.Generic.Collections程序集。

    private void SortCars()
    {
        List<CarSpecs> cars = new List<CarSpecs>();
        List<CarSpecs> carsSorted = new List<CarSpecs>();

        cars.Add(new CarSpecs
        {
            CarName = "Y50",
            CarMaker = "Ford",
            CreationDate = new DateTime(2011, 4, 1),
        });

        cars.Add(new CarSpecs
        {
            CarName = "X25",
            CarMaker = "Volvo",
            CreationDate = new DateTime(2012, 3, 1),
        });

        cars.Add(new CarSpecs
        {
            CarName = "Z75",
            CarMaker = "Datsun",
            CreationDate = new DateTime(2010, 5, 1),
        });

        //More Comprehensive if needed  
        //cars.OrderBy(x => x.CreationDate).ThenBy(x => x.CarMaker).ThenBy(x => x.CarName);

        carsSorted.AddRange(cars.OrderBy(x => x.CreationDate));

        foreach (CarSpecs caritm in carsSorted)
        {
            MessageBox.Show("Name: " +caritm.CarName 
                + "\r\nMaker: " +caritm.CarMaker
                + "\r\nCreationDate: " +caritm.CreationDate);
        }
    }
}

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

#7


1  

If you're after an efficient way of sorting, I'd advise against using bubble sort and go for a quick sort instead. This page provides a rather good explanation of the algorithm:

如果您正在使用有效的排序方法,我建议不要使用冒泡排序,而是快速排序。该页面提供了一个相当好的算法解释:

http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574

http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574

Best of luck!

祝你好运!

#8


1  

I would avoid writing my own sorting algorithm, but if you are going to anyway, have a look at http://www.sorting-algorithms.com/ for some comparrisons of different sorting algorithms...

我会避免编写自己的排序算法,但无论如何,请查看http://www.sorting-algorithms.com/以获取不同排序算法的一些比较...

#9


1  

If you are using 2.0, the following discussion may be useful: C# List<> Sort by x then y

如果您使用的是2.0,则以下讨论可能会有用:C#List <>按x然后y排序

#10


0  

If you use delegates (also known as anonymous methods), you won't have to implement any IComparer / IComparable interfaces.

如果使用委托(也称为匿名方法),则不必实现任何IComparer / IComparable接口。

public static void Main(string[] args)
    {


      List<CarSpecs> list = new List<CarSpecs>();

      list.Add(new CarSpecs("Focus", "Ford", new DateTime(2010,1, 2));
      list.Add(new CarSpecs("Prius", "Toyota", new DateTime(2012,3, 3));
      list.Add(new CarSpecs("Ram", "Dodge", new DateTime(2013, 10, 6));



        list.Sort(delegate (CarSpecs first, CarSpecs second)
        {
            int returnValue = 1;
            if((first != null & second != null))
            {
                if (first.CarName.Equals(second.CarName))
                {
                    if (first.CarMaker.Equals(second.CarMaker))
                    {
                    returnValue = first.CreationDate.CompareTo(second.CreationDate);
                    }
                    else
                    {
                    returnValue = first.CarMaker.CompareTo(second.CarMaker);
                    }
                }
                else
                {
                    returnValue = first.CarName.CompareTo(second.CarName);
                }
            }
            return returnValue;
        });

    }

#1


83  

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.

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

Try this:

尝试这个:

CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));

#2


56  

You could use LINQ:

您可以使用LINQ:

listOfCars.OrderBy(x => x.CreationDate);

EDIT: With this approach, its easy to add on more sort columns:

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

listOfCars.OrderBy(x => x.CreationDate).ThenBy(x => x.Make).ThenBy(x => x.Whatever);

#3


16  

The best approach is to implement either IComparable or IComparable<T>, and then call List<T>.Sort(). This will do all the hard work of sorting for you.

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

#4


14  

Another option would be to use a custom comparer:

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

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
   }
}

which you call like this:

你这样称呼:

yourCarlist.Sort(new CarNameComparer());

Note: I didn't compile this code so you might have to remove typo's

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

Edit: modified it so the comparer compares on creationdate as requested in question.

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

#5


6  

I would just use the build in List.Sort method. It uses the QuickSort algorithm which on average runs in O(n log n).

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

This code should work for you, I change your properties to auto-properties, and defined a static CompareCarSpecs method that just uses the already existing DateTime.CompareTo method.

此代码应该适合您,我将您的属性更改为自动属性,并定义一个静态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);
    }
}

Hope this helps.

希望这可以帮助。

#6


3  

Putting some of the pieces mentioned here together. This compiles and works in C# 4.x and VS2010. I tested with a WinForm. So add the method to the WinForm Main(). You will need the System.Linq and System.Generic.Collections assemblies at least.

将这里提到的一些部分放在一起。这在C#4.x和VS2010中编译和工作。我用WinForm测试过。所以将方法添加到WinForm Main()。您至少需要System.Linq和System.Generic.Collections程序集。

    private void SortCars()
    {
        List<CarSpecs> cars = new List<CarSpecs>();
        List<CarSpecs> carsSorted = new List<CarSpecs>();

        cars.Add(new CarSpecs
        {
            CarName = "Y50",
            CarMaker = "Ford",
            CreationDate = new DateTime(2011, 4, 1),
        });

        cars.Add(new CarSpecs
        {
            CarName = "X25",
            CarMaker = "Volvo",
            CreationDate = new DateTime(2012, 3, 1),
        });

        cars.Add(new CarSpecs
        {
            CarName = "Z75",
            CarMaker = "Datsun",
            CreationDate = new DateTime(2010, 5, 1),
        });

        //More Comprehensive if needed  
        //cars.OrderBy(x => x.CreationDate).ThenBy(x => x.CarMaker).ThenBy(x => x.CarName);

        carsSorted.AddRange(cars.OrderBy(x => x.CreationDate));

        foreach (CarSpecs caritm in carsSorted)
        {
            MessageBox.Show("Name: " +caritm.CarName 
                + "\r\nMaker: " +caritm.CarMaker
                + "\r\nCreationDate: " +caritm.CreationDate);
        }
    }
}

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

#7


1  

If you're after an efficient way of sorting, I'd advise against using bubble sort and go for a quick sort instead. This page provides a rather good explanation of the algorithm:

如果您正在使用有效的排序方法,我建议不要使用冒泡排序,而是快速排序。该页面提供了一个相当好的算法解释:

http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574

http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574

Best of luck!

祝你好运!

#8


1  

I would avoid writing my own sorting algorithm, but if you are going to anyway, have a look at http://www.sorting-algorithms.com/ for some comparrisons of different sorting algorithms...

我会避免编写自己的排序算法,但无论如何,请查看http://www.sorting-algorithms.com/以获取不同排序算法的一些比较...

#9


1  

If you are using 2.0, the following discussion may be useful: C# List<> Sort by x then y

如果您使用的是2.0,则以下讨论可能会有用:C#List <>按x然后y排序

#10


0  

If you use delegates (also known as anonymous methods), you won't have to implement any IComparer / IComparable interfaces.

如果使用委托(也称为匿名方法),则不必实现任何IComparer / IComparable接口。

public static void Main(string[] args)
    {


      List<CarSpecs> list = new List<CarSpecs>();

      list.Add(new CarSpecs("Focus", "Ford", new DateTime(2010,1, 2));
      list.Add(new CarSpecs("Prius", "Toyota", new DateTime(2012,3, 3));
      list.Add(new CarSpecs("Ram", "Dodge", new DateTime(2013, 10, 6));



        list.Sort(delegate (CarSpecs first, CarSpecs second)
        {
            int returnValue = 1;
            if((first != null & second != null))
            {
                if (first.CarName.Equals(second.CarName))
                {
                    if (first.CarMaker.Equals(second.CarMaker))
                    {
                    returnValue = first.CreationDate.CompareTo(second.CreationDate);
                    }
                    else
                    {
                    returnValue = first.CarMaker.CompareTo(second.CarMaker);
                    }
                }
                else
                {
                    returnValue = first.CarName.CompareTo(second.CarName);
                }
            }
            return returnValue;
        });

    }