c# - 列出与另一个列表条件相关的操作

标签 c# linq list indexing

我有两个这样的列表:

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

enter image description here

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

同样;

列表值[0][2][0] = 列表值[0][2][2] = 1。因此必须取 listQ[0][2][0] 和 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/

相关文章:

c# - 无法查询行键设置为 GUID 的项目?

c# - 发布时混淆源代码 (C#)

c# - 记录多实例应用程序最佳实践?

c# - 控制更改其他 UserControl 上的控制

c# - 在列表中查找重复项并根据另一个字段排除项目

c# - 选择 -> 引用自身(当前创建的列表)

list - 如何交换序言列表中的三乘三元素?

java - 在jsp中使用java和html打印列表

list - Haskell:不使用 (++) 连接列表

c# - 遍历 html 字符串以查找所有 img 标签并替换 src 属性值