Sorting a List of objects in C#

后端 未结 11 1862
终归单人心
终归单人心 2020-12-07 18:01
public class CarSpecs
{
  public String CarName { get; set; }

  public String CarMaker { get; set; }

  public DateTime CreationDate { get; set; }
}
相关标签:
11条回答
  • 2020-12-07 18:13

    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.

    0 讨论(0)
  • 2020-12-07 18:15

    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.

        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; }
    } 
    
    0 讨论(0)
  • 2020-12-07 18:17

    To extend the answer of Noldorin, in order to sort a list with int datatype this can be used:

    listName.Sort((x, y) =>  x.CompareTo(y));
    

    Or if you have a complex object in the list:

    inventoryList.Sort((x, y) =>  x.stockNumber.CompareTo(y.stockNumber));
    
    0 讨论(0)
  • 2020-12-07 18:19

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

    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;
            });
    
        }
    
    0 讨论(0)
  • If you are using 2.0, the following discussion may be useful: C# List<> Sort by x then y

    0 讨论(0)
  • 2020-12-07 18:21

    I would just use the build in List.Sort method. It uses the QuickSort algorithm which on average runs in 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.

    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.

    0 讨论(0)
提交回复
热议问题