caraLinq
caraLinq

Reputation: 71

Try to sort a List of Object in C#

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

Upvotes: 1

Views: 78

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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);
});

Upvotes: 2

Codor
Codor

Reputation: 17595

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();

Upvotes: 3

Related Questions