[英]Converting a 2d array into a 2d array of a different type. int[,] => ushort[,]
我試圖找到一種方法,可以在一行代碼中將一種類型的二維數組轉換為另一種類型。
這是一種個人學習的體驗,而不是需要一次完成!!
我到目前為止已經將其轉換為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數組?
編輯:
我已經更新了我的代碼。
現在,我得到了一個ushort [,]的IEnumerable集合。
我現在需要找到一種方法將所有這些合並為一個ushort [,]
為了保持二維結果,我能想到的最好的辦法是:
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));
使用顯式ushort
為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];
}
如果您對鋸齒狀數組而不是多維數組感興趣,請使用此方法。
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
怎么樣:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.