-1

I have an array of tuples and want to get tuple with a max second element without for cycles. I think it should be some linq statement or something similar:

var a = new Tuple<string, int>[n];

// *initializing*

Tuple<string, int> mx = a.Max(t => t.Item2);

Also, it must have O(n) complexity

majorro
  • 61
  • 1
  • 2
  • 8
  • Does this answer your question? [How to perform .Max() on a property of all objects in a collection and return the object with maximum value](https://stackoverflow.com/questions/1101841/how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-return-th) or you can use MoreLINQ's MaxBy function – Charlieface Feb 14 '21 at 01:03
  • Yes, this is exactly what I searched for, thank you – majorro Feb 14 '21 at 01:05
  • It would have been quicker to just write a for loop than writing a question let alone waiting for an answer to a library that does exactly the same thing – TheGeneral Feb 14 '21 at 01:22
  • Well, I was just curious to know, thanks for pointing on an obvious fact:) – majorro Feb 14 '21 at 02:32

1 Answers1

0

If you sort by the ordering constraint, then you can get the first item.

    // Populate a Sample
    var a = new Tuple<string, int>[10];
    for(int i = 0; i <= 9; i++)
    {
        var t = new Tuple<string, int>(i.ToString(), i);
        a[i] = t;
    }
    
    // Get First Item with Highest Value
    Console.WriteLine(a.OrderByDescending(c => c.Item2).First());
Ctznkane525
  • 7,297
  • 3
  • 16
  • 40