Home > other >  Get max or min Value in List<Tuple<double, double>> _val in C#
Get max or min Value in List<Tuple<double, double>> _val in C#

Time:10-06

Hi2,

How can I get a min and max Value from List<Tuple<double, double>> tupleList ?

I know that I can get min or min in List<double> onlyList via

onlyList.Max();
onlyList.Min();

But how is it with List with Tuple ? Should I parse the Tuple to a new list then call "Max() / Min()" ?

For example if i have this

tupleList.Add(new Tuple<double, double>(11, 3));
tupleList.Add(new Tuple<double, double>(10, 5));
tupleList.Add(new Tuple<double, double>(12, 2));
tupleList.Add(new Tuple<double, double>(13, 0));
tupleList.Add(new Tuple<double, double>(15, 4));
tupleList.Add(new Tuple<double, double>(14, 1));

I wanna compare the first double in each tuple (from 10 - 15) and get 10 and 15 as min and max, and then also the second double in each tuple (from 0 - 5) and get 0 and 5 as min and max respectively.

Thank you for your insight guys! ^^,

CodePudding user response:

If you want the min/max of any values in the list of tuples, you could do:

onlyList.Min(t => t.Item1 < t.Item2 ? t.Item1 : t.Item2);
onlyList.Max(t => t.Item1 > t.Item2 ? t.Item1 : t.Item2);

If you need the max of the first or second item, use

onlyList.Max(t => t.Item1);

And similarly for Min.

There are other ways - create a "flattened" list of all items (e.g. with SelectMany) and call max on that, etc. Use whatever makes the most sense to you. I would not expect a significant performance difference unless you do something that iterates over the list multiple times.

CodePudding user response:

public (double, double) Min(IEnumerable<(double, double)> items)
{
    (double, double) result = (int.MaxValue, int.MaxValue);
    foreach(var item in items)
    {
        result.Item1 = Math.Min(result.Item1, item.Item1);
        result.Item2 = Math.Min(result.Item2, item.Item2);
    }
    return result;
}


public (double, double) Max(IEnumerable<(double, double)> items)
{
    (double, double) result = (int.MinValue, int.MinValue);
    foreach(var item in items)
    {
        result.Item1 = Math.Max(result.Item1, item.Item1);
        result.Item2 = Math.Max(result.Item2, item.Item2);
    }
    return result;
}


var tupleList = new List<(double, double)> {
    (11,3),
    (10,5),
    (12,2),
    (13,0),
    (15,4),
    (14,1)
};

var minResult = Min(tupleList);
var maxReslut = Max(tupleList);

Alternatively:

var tupleList = new List<(double, double)> {
    (11,3),
    (10,5),
    (12,2),
    (13,0),
    (15,4),
    (14,1)
};

var minResult = (tupleList.Min(i => i.Item1), tupeList.Min(i => i.Item2));
var maxResult = (tupleList.Max(i => i.Item1), tupeList.Max(i => i.Item2));

The above is a lot less code, but it's four separate passes through the list instead of just two.

  •  Tags:  
  • c#
  • Related