1

I'm making a program in c# and I got a list with objects which I want to sort with c#. I can't get it working nor do I understand how it should be implemented.

I did some research for which algorithm I should use and came up with merge sort because it's always n(log n) and doesn't rely on a lucky chance with the pivot like quick sort to achieve it.

Anyways so far why I chose that and want it. :)

it's a list with weight each weight contains a date and a bodyweight. I want to get it sorted on the date and make the method return the sorted list.

Could someone help me to achieve this. You would help me out a lot :)

Thanks in advance

JordyRitzen
  • 592
  • 5
  • 21
  • 1
    1)Implement IComparable interface in your class. 2)Add your object to a List. 3)Call Sort() on the list object – George Vovos Sep 07 '14 at 15:08
  • Also http://stackoverflow.com/questions/3163922/sort-a-custom-class-listt – George Vovos Sep 07 '14 at 15:09
  • 1
    Yes, `IEnumerable.Sort` will perform Quicksort but it is usually better than Mergesort. You need to have a really good reason to go with Mergesort, and above all that `IEnumerable.Sort` is an excellent Quicksort implementation. Read this: http://stackoverflow.com/questions/70402/why-is-quicksort-better-than-mergesort – Patrice Gahide Sep 07 '14 at 15:18

1 Answers1

2

You can use linq to sort collections, for example:

public IEnumerable<Weight> GetSortedWeights()
{
    var weights = new List<Weight>() { new Weight { Date = DateTime.Now, BodyWeight = 80 }, ... };

    return weights.OrderBy(x => x.Date);
}
Teppic
  • 2,506
  • 20
  • 26