911Rapid
911Rapid

Reputation: 199

How to get specific columnar maximums in List of arrays?

I have a list "XYZarr" filled with array of integers as shown below.

        int[] intarr1 = new int[3]{  1, 4, 15};
        int[] intarr2 = new int[3] { 10, 5, 8};
        int[] intarr3 = new int[3] { 7, 8, 12 };
        int[] intarr4 = new int[3] { 7, 8, 9 };

        List<int[]> XYZarr = new List<int[]>() { intarr1, intarr2, intarr3, intarr4 };

I want to get only three indexes from the list where int[2] is maximum(i.e third entry). so the resulting indexes should be 0,2,3 of the list "XYZarr"

I can do it by looping through the list , but i want to use LinQ for this. I am not able to phrase the question properly, but..i hope you get my point

Upvotes: 0

Views: 49

Answers (2)

Yacoub Massad
Yacoub Massad

Reputation: 27871

I am assuming that "int[2] is maximum" means that the 3rd element in the array is the maximum element in that array.

Here is how:

var result = 
    XYZarr
    .Select((list,index)
        => new {list,index})
    .Where(x => x.list.Max() == x.list[2])
    .Select(x => x.index)
    .ToList();

If XYZarr contains more than 3 arrays and you just want to get 3 results, then use the Take method like this:

var result = 
    XYZarr
    .Select((list,index)
        => new {list,index})
    .Where(x => x.list.Max() == x.list[2])
    .Select(x => x.index)
    .Take(3)
    .ToList();

Upvotes: 1

Ivan Stoev
Ivan Stoev

Reputation: 205929

How about this:

var result = Enumerable.Range(0, XYZarr.Count)
    .OrderByDescending(i => XYZarr[i][2])
    .Take(3)
    .ToList();

Upvotes: 1

Related Questions