如何将整数数组转换为整数?

8
我希望学习如何在C#中将int数组转换为int。但是我想要将int与数组中的值连接起来。
例如:
int[] array = {5, 6, 2, 4};

将会被转换为一个等于5624的整数。

提前感谢任何帮助。


4
如果数组中的数字组成一个无法装入 int 的数,会发生什么? - Jon
2
那么不在0...9范围内的数组项怎么办? - Danny Varod
14个回答

0

如果你理解了十进制系统的工作原理,这将很容易。

所以让我为您解释一下:十进制数字包含基于十进制的单个数字。

这意味着您必须遍历此数组(向后!)并乘以10 ^

例如5624表示:(5 * 10 ^ 3)+(6 * 10 ^ 2)+(2 * 10 ^ 1)+(4 * 10 ^ 0)

请还要考虑:http://en.wikipedia.org/wiki/Horner_scheme


0

只是为了好玩...

arr.Select((item, index) => new { Item = item, Power = arr.Length - (index - 1) }).ToList().ForEach(item => total += (int)(Math.Pow(10, item.Power) * item.Item));

0

如果你想将 int[] 转换为 int?[] 数组,我只能使用 for 循环 :(

 int[] First = Person.Select(p => p.ShiftID).ToArray();
                int?[] converted = new int?[First.Length];
                for (int im = 0; im < First.Length; im++)
                    converted[im] = First[im];

我找不到一种高性能的转换方法。


0

你可以使用字符串流(包括 "sstream")

using namespace std; int main() {

int arr[3]={3,2,4};     //your array..

stringstream ss;

ss<<arr[0];   //this can be run as a loop
ss<<arr[1];
ss<<arr[2];


int x;
ss>>x;

cout<<x;        //simply the int arr[3] will be converted to int x..

请记得添加 **#include<sstream>**。 - Ramith Hettiarachchi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接