【问题标题】:Converting a 2d array into a 2d array of a different type. int[,] => ushort[,]将二维数组转换为不同类型的二维数组。 int[,] => ushort[,]
【发布时间】:2023-04-06 20:19:02
【问题描述】:

我试图找到一种方法,可以在一行代码中将一种类型的二维数组转换为另一种类型。

这是个人的学习体验,而不是需要一条线完成!!

我已经把它转换成IEnumerable<Tuple<ushort,ushort>>。不知道从这里去哪里。

int[,] X = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

var Result = (from e in X.OfType<int>() select e)
                .Select(S => (ushort)S)
                .Select((value, index) => new { Index = index, Value = value })
                      .GroupBy(x => x.Index / 2)
                      .Select(g => new ushort[,] { { g.ElementAt(0).Value, 
                                                     g.ElementAt(1).Value } });

需要以某种方式将元组集合转换为 ushort[,]

编辑:

只是澄清问题。

如何使用 linq 中的一行代码将 int 2d 数组转换为 ushort 2d 数组?

编辑:

我已经更新了我的代码。

我现在得到了一个 IEnumerable 的 ushort[,] 集合。

我现在需要找到一种方法将所有这些连接成一个 ushort[,]

【问题讨论】:

标签: c# .net linq


【解决方案1】:

我能想出的保持二维结果的最佳方法是:

var input = new [,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
var output = new ushort[input.GetUpperBound(0) + 1, input.GetUpperBound(1) + 1];
Buffer.BlockCopy(input.Cast<int>().Select(x => (ushort)x).ToArray(), 0, output, 0, input.GetLength(0) * input.GetLength(1) * sizeof(ushort));

【讨论】:

  • 太棒了。由于它太短了,我们需要定义一个输出数组。
  • 您可以改用new ushort[input.GetLength(0), input.GetLength(1)
【解决方案2】:

使用显式强制转换为 ushort 我们可以做到这一点,我留给您探索转换中的后果并解决它们。

int[,] X = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
ushort[,] shortArray = new ushort[X.GetUpperBound(0)+1, X.GetUpperBound(1)+1];

for (int i = 0; i <= X.GetUpperBound(0); ++i) 
{
    for(int j=0;j<= X.GetUpperBound(1);j++)

        shortArray[i, j] = (ushort)X[i,j];         
}

如果您对 Jagged 数组而不是多维数组感兴趣,请使用它。

var jagged =  X.Cast<int>()     
               .Select((x, i) => new { Index = i, Value = x })
               .GroupBy(x => x.Index / (X.GetUpperBound(1) +1))
               .Select(x => x.Select(s=> (ushort)s.Value).ToArray())
               .ToArray();

工作example

【讨论】:

  • 是的,我知道它很容易使用循环。我专门尝试使用单个 linq 行来完成此操作。
  • 转换很简单,但是多维数组的创建是个问题,用锯齿数组怎么样(第二种方法)?
【解决方案3】:

怎么样:

var Result = X.OfType<int>().Select(s => new { Index = (s + 1) / 2, Value = s})
                            .GroupBy(g => g.Index)
                            .Select(s => s.Select(g => (ushort)g.Value).ToArray())
                            .ToArray();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2016-02-18
  • 2018-02-19
相关资源
最近更新 更多