Search code examples
c#maxminlis

The most efficient way to get object with max value from list of objects


I have an object called entry. It has min and max in float and fileName in string. And those objects are stored in a list

List<Entry> minMaxList = new List<Entry>();

I need to find an object(s) with the highest value and with the minimum value alongside with its file name.

So if I have an array like this

       Entry1                    Entry2                  Entry3
min  max    filename        min  max    filename      min  max    filename
| 2 | 120 |  file1.txt |  | 2 | 150 |  file1.txt |  | 5 | 150 |  file1.txt |     

I want to get that the objects with the lowest value are Entry1 and Entry2 and objects with the highest value are Entry2 and Entry3

I tried this:

var max =  minMaxList.Max(r => r.getMax())

which works good, but it returns me a single value, without any other information about where it came from. I need either the whole object, or at least the filenames in which this value is. I wonder if it can be done in a single command, or if I have to then iterate the list again and find all the entries base on the min and max selected earlier.


Solution

  • You can always filter the enumerable instead of only letting the maximum value through:

    var maxvalue = minMaxList.Max(w => w.getMax());
    var maxitems = minmaxlist.Where(w => w.getMax() == maxvalue);