How to Get a List<double> with the max value in the lists in a nested list by index C#

Marino Liranzo 81 Reputation points
2023-03-10T03:31:59.6+00:00

Hello people of the forum,

I have a nested list with List<List<double>> each list contains the same number of elements. I want to obtain a List<double> that contains the maximum value of all the lists by index, that is, the maximum value of all the indexes of each list. example:

List<List<double'>> myNestedList ....

List<double> list1 = new List<double>(){1.30, 2.33, 4.21, 4.02}

List<double> list2 = new List<double>(){3.21, 2.48, 6.12, 1.55}

List<double> list3 = new List<double>(){2.23, 4.51, 3.66, 2.56}

List<double> list4 = new List<double>(){1.11, 0.66, 3.82, 2.41}

myNestedList.Add(list1); myNestedList.Add(list2); myNestedList.Add(list3); myNestedList.Add(list4);

My result must be a list<double>() { 3.21, 4.51, 6.12, 4.02} each value is the maximum for index.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,198 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 26,426 Reputation points Microsoft Vendor
    2023-03-10T05:55:15.21+00:00

    Hi @Marino Liranzo ,

    Please check if the following code helps.

            private List<double> GetMaxValue(List<List<double>> list) {
                List<List<double>> newList = new List<List<double>>();
                List<double>res=new List<double>();
                for (int i = 0; i < list[0].Count; i++) {
                    Console.WriteLine(i);
                    List<double> a = new List<double>();
                    foreach (List<double> l in list) {
                        a.Add(l[i]);
                    }
                    newList.Add(a);
                }
                foreach (List<double> l in newList) {
                    res.Add(l.Max());
                }
                return res;
            }
               
    

    Best Regards.
    Jiachen Li
    ----------
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful