C# Help: Sorting a List of Objects in C# [duplicat

2019-03-25 02:59发布

问题:

Possible Duplicates:
Sort objects using predefined list of sorted values
C# Help: Sorting a List of Objects in C#

Double Post

Sorting a List of objects in C#

public class CarSpecs
{

    public CarSpecs()
    {
    }

    private String _CarName;
    public String CarName
    {
        get { return _CarName; }
        set { _CarName = value; }
    }



    private String _CarMaker;
    public String CarMaker
    {
       get { return _CarMaker;}
       set { _CarMaker = value; }
    }


    private DateTime _CreationDate;
    public DateTime CreationDate
    {
        get { return _CreationDate; }
        set { _CreationDate = value; }
    }
}

This is a list and I am trying to figure out an efficient way to sort this list List<CarSpecs> 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?

Thanks

回答1:

CarList = CarList.OrderBy( x => x.CreationDate ).ToList();


回答2:

First, using the shorthand syntax introduced in .Net 3.5, you could make this class definition a lot shorter:

public class CarSpecs
{
    public CarSpecs() { }

    public String CarName { get; set;
    public String CarMaker { get; set; }
    public DateTime CreationDate { get; set; }
}

This will compile into the exact same class as the one you have above.

Secondly, you can easily sort them using Lambda expressions or LINQ:

var linq = (from CarSpecs c in CarList
            orderby c.CreationDate ascending
            select c) as List<CarList>;

var lambda = CarList.OrderBy(c => c.CreationDate).ToList();


回答3:

Don't write your own sorting algorithm. .NET has an Array.Sort() method specifically for things such as this.

Since you have a custom object, you need to define how to compare 2 objects so the sorting algorithm knows how to sort them. You can do this 1 of 2 ways:

  1. Make your CarSpecs class implement the IComparable interface
  2. Create a class that implements IComparer and pass that in as a parameter to Array.Sort() along with your array.


回答4:

There are already existing sorting algorithms in the BCL - Array.Sort() and List.Sort(). Implement an IComparer class that determines the sort order using the CreationDate, then put all the objects into an array or list and call the appropriate Sort() method



标签: c# sorting class