Hakan
Hakan

Reputation: 45

How to sort a List of arrays by an element at a specified index in the array

I have a list<> of int arrays created like this

List<uint[]> onMinterm = new List<uint[]>();    

and it has got 1000 members. Every list members has 3 unsigned integers, I add my arrays just like that

uint[] sayi= new uint[3];    
sayi[0] = 34432; sayi[1] = 63533; sayi[2] = 12;    
onMinterm.Add(sayi);

I want to sort my 1000 list (onMinterm) according to each 3rd member (sayi[2]). List will be sorted in decending order. Sample member should be at the end as its 3rd value is very small like 12.

Upvotes: 2

Views: 93

Answers (2)

glenebob
glenebob

Reputation: 1983

You can sort a List<> in place.

    class IntArrayComparer : IComparer<int[]>
    {
      public int Compare(T left, T right)
      {
        return right[2].CompareTo(left[2]);
      }
    }

    myList.Sort(new IntArrayComparer());

Upvotes: 1

Alex
Alex

Reputation: 13244

I want to sort my 1000 list (onMinterm) according to each 3rd member (sayi[2]). List will be sorted descending.

You can do this, if you are ok with getting an IOrderedEnumerable as the result.

var ordered = onMinterm.OrderByDescending(x => x[2]);

If you want to do an in-place sort:

onMinterm.Sort((x1, x2)=> x2[2].CompareTo(x1[2]));

Upvotes: 3

Related Questions