Reputation: 3
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?
Upvotes: 0
Views: 100
Reputation: 68640
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.
Upvotes: 2
Reputation: 7918
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,
Upvotes: 0