gpt4 book ai didi

c# - 在关键索引上使用 LINQ 连接多维数组

转载 作者:行者123 更新时间:2023-11-30 16:29:58 25 4
gpt4 key购买 nike

我有 N 个多维源数据数组,每个数组的列数相同(本例中 C=4),但行数任意:

var array1 = new double[,]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};

var array2 = new double[,]
{
{ 1, 2, 5, 6 },
{ 7, 8, 9, 10 },
{ 9, 10, 11, 12 }
};

var array3 = new double[,]
{
{ 1, 2, 7, 8 },
{ 13, 14, 15, 16 }
};

...
var arrayN = new double[,] { ... };

我还有一个数组,它指定源数组中的哪些索引将用作连接键:

var keyArray = new int[] { 0, 1 };

我需要按照结果数组的方式加入数组:

var result = new double[,]
{
// The length of each element in this array will be (C x N),
// the first C elements will be from array1, the next C from
// array2, and so on, and nulls used for arrays elements that
// are not included in the join (keys don't match).
//
// The number of rows in this array will be the number of distinct key combinations.
{ 1, 2, 3, 4, 1, 2, 5, 6, 1, 2, 7, 8 },
{ 5, 6, 7, 8, null, null, null, null, null, null, null, null },
{ 9, 10, 11, 12, 9, 10, 11, 12, null, null, null, null },
{ null, null, null, null, 7, 8, 9, 10, null, null, null, null },
{ null, null, null, null, null, null, null, null, 13, 14, 15, 16 }
};

我想我需要从每个源数组中选择不同的键并循环遍历所有数据并比较每一行等以填充结果数组。但是,应该有一种使用 LINQ 执行此操作的更有效方法 - 谁能帮忙?

最佳答案

如果您使用 double[][] 而不是 double[,],这是一个解决方案

var array1 = new double[][]
{
new double[] {1,2,3,4},
new double[] {5,6,7,8},
new double[] {9,10,11,12}
};

var array2 = new double[][]
{
new double[] {1,2,5,6},
new double[] {7,8,9,10},
new double[] {9,10,11,12}
};

var key = new int[] { 0, 1 };

double?[][] result = (from a in array1
from b in array2.Where(bi => key.Select(k => bi[k] == a[k])
.Aggregate((k1, k2) => k1 && k2))
.DefaultIfEmpty()
select a.Select(an => (double?)an)
.Concat(b == null ?
a.Select(an => (double?)null) :
b.Select(bn => (double?)bn))
.ToArray()
).Union
(from b in array2
from a in array1.Where(ai => key.Select(k => ai[k] == b[k])
.Aggregate((k1, k2) => k1 && k2))
.DefaultIfEmpty()
where a == null
select b.Select(bn => (double?)null)
.Concat(b.Select(bn =>(double?)bn))
.ToArray()
).ToArray();

关于c# - 在关键索引上使用 LINQ 连接多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6031980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com