Possible Duplicates:
Sort objects using predefined list of sorted values
C# Help: Sorting a List of Objects in C#Double Post
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
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
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:
CarSpecs
class implement theIComparable
interfaceIComparer
and pass that in as a parameter toArray.Sort()
along with your array.First, using the shorthand syntax introduced in .Net 3.5, you could make this class definition a lot shorter:
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: