views:

1728

answers:

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

+16  A: 

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.

Try this:

CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));
Noldorin
I think he want's to sort, first by Car, then by Make, then by Date...
Eoin Campbell
@Eoin: It's slightly ambiguous, I admit. I still believe he meant "Car Make Date" as one property, referring to `CreationDate`.
Noldorin
+1 from for using lambda expressions!
Egil Hansen
+7  A: 

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.

Andy
+1 to counter the pointless -1 that someone else did. Nothing wrong with this suggestion.
tomfanning
+1  A: 

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

Best of luck!

Banang
+9  A: 

You could use 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);
Arjan Einbu
Yeah, this will do the job too. It will however have worse performance than using List.Sort, since it's based around LINQ (i.e. IEnumerable<T> objects), though from the original question that wouldn't seem to be a big deal. The only real difference is that this returns a new object (which you then have to convert to a list using `ToList()`), whereas List.Sort performs the sort on the current instance.
Noldorin
@Noldorin. Yeah, your suggestion of using List.Sort(comparisson) could be quicker...
Arjan Einbu
+4  A: 

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.

Peter
Nothing wrong with this, but far more than you need!
Noldorin
Modified my answer to match your comment. It is way to go to have full control over the sorting. But that may be too much in this case :-)
Peter
+1  A: 

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

Arjan Einbu
+3  A: 

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.

Egil Hansen
This is a good solution if you don't have C# 3.0 available (i.e. no lambdas).
Noldorin
+1  A: 

If you are using 2.0, the following discussion may be useful: http://stackoverflow.com/questions/289010/c-list-sort-by-x-then-y

Byron Ross