我有两个这样的 list :

public static List<List<List<double>>> listQ = new List<List<List<double>>>();
public static List<List<List<double>>> listVal = new List <List<List<double>>>();

2个列表也具有相同的大小。我想要一些与listVal相关的listQ操作:
  • 如果listVal的任何索引具有相同的值,我想在相同的索引中获取平均listQ的值。

  • 例如:
    listVal[0][0][ 1] = listVal[0][0][2] = 3.
    

    因此,我希望listQ的相同索引相同。
    (listQ[0][0][ 1] + listQ[0][0][2]) / 2 = (26.5 + 20.4) / 2 = 23.45.
    

    现在,每个这些索引必须具有23.45:
    listQ[0][0][ 1] = 23.45
    
    listQ[0][0][ 2] = 23.45
    

    同样地;
    listVal[0][2][0] = listVal[0][2][2] = 1。因此,必须采用listQ[0][2][0] and listQ[0][2][2]的平均值。

    我怎样才能做到这一点?

    编辑:@Roman Izosimov和@Petko Petkov的解决方案正常工作。哪一个性能更高?你怎么看?

    最佳答案

    适用于lulz的LINQ解决方案:)

    List<List<List<double>>> listVal = new List<List<List<double>>>(){
        new List<List<double>>{
            new List<double>(){1,1,3},
            new List<double>(){2,1,2},
            new List<double>(){1,2,3}
        },
        new List<List<double>>{
            new List<double>(){2,1,3},
            new List<double>(){2,4,2},
            new List<double>(){3,1,3}
        },
        new List<List<double>>{
            new List<double>(){4,1,1},
            new List<double>(){4,2,1},
            new List<double>(){4,3,1}
        }
    };
    List<List<List<double>>> listQ = new List<List<List<double>>>(){
            new List<List<double>>{
            new List<double>(){3,7,4},
            new List<double>(){8,15,23},
            new List<double>(){11,13,17}
        },
        new List<List<double>>{
            new List<double>(){90,3,7},
            new List<double>(){5,7,12},
            new List<double>(){7,14,21}
        },
        new List<List<double>>{
            new List<double>(){32,4,1},
            new List<double>(){55,12,8},
            new List<double>(){3,5,8}
        }
    };
    
    
    //Linq awesomeness
    var qry = listVal.SelectMany((l1, i0) =>
                    l1.SelectMany((l2, i1) =>
                        l2.Select((ele, i2) =>
                            new { i0, i1, i2, gVal = ele, qVal = listQ[i0][i1][i2] })))
                    .GroupBy(x => new { x.i0, x.i1, x.gVal }) // if you want to average across the innermost lists only
                    //.GroupBy(x => x.gVal)                   //if you want to average acreoss the whole data
                    .SelectMany(x => x.Select(e => new { e.i0, e.i1, e.i2, avg = x.Average(y => y.qVal) }));
    foreach (var e in qry)
    {
        listQ[e.i0][e.i1][e.i2] = e.avg;
    }
    

    关于c# - 列出与其他列表条件相关的操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21131736/

    10-13 06:24