2016-05-09 52 views
0

擁有一個ushort數組,ushort[]如何將ushort數組[44,55]轉換爲單個加入的ushort 4455?數組總是有兩個元素。將一個ushort []數組轉換爲C#中的單個ushort

ushort[] test = new ushort[2]; 
test[0] = 44; 
test[1] = 55; 
// Here I want to convert the ushort[] to a unique ushort value 4455 
usortValue = ? 
return usortValue; 

我期待一個.join功能String沒有,但它不可能與ushort

在此先感謝

+4

願與您在溢出的情況下該怎麼辦? –

+0

@DovydasSopa這對我來說不是問題,因爲我只需要連接長度爲2的數組。 –

+4

像[44,5]這樣的對會發生什麼? - 結果應該是445還是4405? – PaulF

回答

4

可以聚集,與謂語是「轉換爲字符串,並置,並解析回USHORT」,但遲早(sooner!)你要溢出。

ushort[] test = new ushort[2]; 
test[0] = 44; 
test[1] = 55; 
var result = test.Aggregate((p,c) => ushort.Parse((p.ToString() + c.ToString()))); 

活生生的例子:http://rextester.com/VKV9570

+0

這段代碼返回的結果是'5544' - 這真的是OP想要的嗎? –

+0

@MthetheWWatson - 不,我可能有'c'和'p'的錯誤方式:D(現在已修復) – Jamiec

1
ushortValue = Convert.ToUInt16(test[0].ToString() + test[1].ToString()); 
2

如何數字轉換爲字符串,並加入他們?

var result =string.Join("",test.Select(x=>x.ToString()));  
Convert.ToUInt16(result); 

Demo