0

I have list list myList which has over 12 million elements. myClass has two properties ie. "gt" and "gm". I want to find maximum "gt" elements and choose that has min "gm". forexample: let myList such as:(first column is gt other is gm)

  4 1
  5 2
  7 1
  8 3
  4 3
  2 2
  8 7
  1 7
  8 2

I want to get the myClass element which has gt=8,gm=2. Where can I start?is sorting gt descending order an efficent way?

Myesil
  • 3
  • 2
  • If you're looking for one element, sorting is not an efficient way. O(2n) = O(n) < O(n log n). – Mephy Nov 22 '14 at 19:36
  • This question has already been answered - see [here](http://stackoverflow.com/questions/1101841/linq-how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-ret) – user2008934 Nov 22 '14 at 19:48

2 Answers2

2
myList.OrderByDescending(x => x.gt)                                  
      .ThenBy(x => x.gm)
      .First();

A more efficient, but less readbale way would be using Enumerable.Aggregate which iterates the collection once, and thus executes in O(n) time:

var seed = myList.First()
myList.Aggregate(seed, 
        (max, item) => {
            if(item.gt > max.gt)
                return item;
            if(item.gt == max.gt && item.gm < max.gm)
                return item;
            return max;
        });

Before going with the more efficient approach, measure both and make sure the readability-performance trade-off is worth it.

Rahul Singh
  • 20,580
  • 5
  • 32
  • 49
dcastro
  • 59,520
  • 20
  • 126
  • 147
  • thanks for answering.unfortunately it gives "nullreferenceexception was unhandled" exception at "if(item.gt > max.gt)" when I hover my mouse on "item", it was null. – Myesil Nov 22 '14 at 20:33
  • @Myesil That's because your list contains null items. Just filter those out, by chaining `.Where(item => item != null)` before calling `Aggregate`/`OrderByDescending` – dcastro Nov 22 '14 at 20:51
0

There is an Array.Max() method, which can be useful in your case, provided that you converted List to Array (using for example, List<T>.ToArray() Method as explained here: http://msdn.microsoft.com/en-us/library/x303t819%28v=vs.110%29.aspx). Regards,

Alexander Bell
  • 7,556
  • 2
  • 22
  • 37