将2d数组转换为其他类型的2d数组. int [,] => ushort [,] [英] Converting a 2d array into a 2d array of a different type. int[,] => ushort[,]

查看:89
本文介绍了将2d数组转换为其他类型的2d数组. int [,] => ushort [,]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to find out a way to convert a 2d array of one type to another in a single line of code.

这是一种个人学习体验,而不是需要一行完成!!

This is a personal learning experience rather than a need to do it in one line!!

到目前为止,我已经将其转换为IEnumerable<Tuple<ushort,ushort>>.不知道从这里去哪里.

Ive gotten so far as to convert it into IEnumerable<Tuple<ushort,ushort>>. Not sure where to go from here.

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 [,]

Need to somehow convert the collection of Tuples into a ushort[,]

只需澄清这个问题即可.

Just clarifying the question.

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

How do I convert a int 2d array into a ushort 2d array using a single line of code in linq?

我已经更新了我的代码.

Ive updated my code.

我现在有了它,从而得到了IEnumerable的ushort [,]集合.

I now have it resulting in a IEnumerable collection of ushort[,].

我现在需要找到一种将所有这些合并为一个ushort [,]

I need to now find a way to concatonate all these into a single ushort[,]

推荐答案

为了保持二维结果,我想出的最好办法是:

The best I could come up with to keep the result two dimensional is this:

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));

这篇关于将2d数组转换为其他类型的2d数组. int [,] =&gt; ushort [,]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆