Sorting a List of objects in C#

后端 未结 11 1902
终归单人心
终归单人心 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: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 cars = new List();
            List carsSorted = new List();
    
            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; }
    } 
    

提交回复
热议问题