1

I'm trying to sort a c # object list, the object is composed like this: an int num and a string alphabet. I wish a list like that :

 - element 1 : num : 2 alphabet : A
 - element 2 : num : 1 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

become like that :

 - element 1 : num : 1 alphabet : A
 - element 2 : num : 2 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

I already did that :

myList.Sort(MyObject p1, MyObject p2) {
  p1.num;
  p2.Type;
  //code but i don't know what
});

Does anyone know how to do it? thank you very much

caraLinq
  • 71
  • 6

2 Answers2

3

As apparently lexicographic sorting is desired, the list can be sorted using the Linq extension methods OrderBy and ThenBy (which are documented here) as follows.

myList = MyList.OrderBy(x => x.alphabet).ThenBy(x => x.num).ToList();
Codor
  • 17,447
  • 9
  • 29
  • 56
  • the desired output has `num` descending in case of alphabet `A` and `num` ascending in case of alphabet `B` – fubo Nov 15 '17 at 14:07
  • 1
    Yes but i work with huge list and if i use Linq, i will have a serious issue of performance, no ? – caraLinq Nov 15 '17 at 14:08
2

If you want to sort existing list inplace:

myList.Sort((left, right) => {
  int r = string.Compare(left.alphabet, right.alphabet);

  if (r != 0)
    return r;
  else
    return left.num.CompareTo(right.num);
});
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215