How do I get the columnar minimums in a list of arrays?

I have an array of doubles stored in a list like below. I want to get the minimum from each column. I know I can iterate over the list somehow and get the minimum. But is there an easier way to get the same thing using List.Min () from each column?

List<double[]> BoxCoords = new List<double[]>();

<!-----------------Console output of BoxCoords List------------------------------!>

 8.03698858873275  | -1622.419367705   | 180.603950687759   //List Entry 1
 8.03698858855283  | -1622.41905090503 | -220.203952098008  //List Entry 2 
-7.70512234523364  | -1665.73116372802 | -220.204298594721  //List Entry 3

      

+3


source to share


2 answers


Assuming your columns are defined by the ordinals of the wrapped arrays rather than the values ​​in each row, here's the index

overload
of method Select

to mute the data (with SelectMany

) and then regroup the data by index, after which the application Min

is a formality:

var columnMins = BoxCoords
    .SelectMany(bc => bc.Select((v, idx) => new {Idx = idx, Val = v}))
    .GroupBy(up => up.Idx)
    .Select(grp => grp.Min(x => x.Val));

      

You can add .ToArray()

to the end if you need this as an arraydouble



[- 7.70512234523364, -1665.73116372802, -220.204298594721]

.NET Fiddle Demo

+6


source


for the line:

List<double[]> BoxCoords = new List<double[]>();
var result = BoxCoords.Select(x=>x.Min()).ToList();

      



for a column:

var result = new List<double>();
for (int i = 0; i < BoxCoords[0].Length; i++)//care! exception for jugged arrays
{
    result.Add(BoxCoords.SelectMany(x => x.Skip(i).Take(1).ToList()).ToList().Min());
}

      

+6


source







All Articles