简体   繁体   English

将Int List转换为Integer

[英]Convert Int List Into Integer

This is a bit of an odd case I must admit, but I'm trying to find a succinct and elegant way of converting a List<int> into an actual int . 这是我必须承认的一个奇怪的情况,但我试图找到一种将List<int>转换为实际int的简洁而优雅的方法。 For example, if my list contained entries 1, 2, and 3, then the final integer would be 123. The only other way I thought of doing it was converting the array to a string and then parsing the string. 例如,如果我的列表包含条目1,2和3,那么最后的整数将是123.我想到的另一种方法是将数组转换为字符串然后解析字符串。

Any hints? 任何提示?

Iterate the list, as if adding a sum, but multiply the running total by 10 at each stage. 迭代列表,就像添加一个总和,但在每个阶段将运行总数乘以10。

int total = 0;
foreach (int entry in list)
{
    total = 10 * total + entry;
}
List<int> l = new List<int>();
// add numbers
int result = int.Parse(string.Join(",", l).Replace(",", ""))

You'd have to take care if the list is long enough so that the resulting number would exceed the limits for an int though. 如果列表足够长,您必须小心,以便结果数字超过int的限制。

I think you suggestion is pretty good, something like this works: 我认为你的建议非常好,这样的工作:

var list = new List<int>() { 1, 2, 3, 4 };
var listAsString = String.Join("", list.ConvertAll(x => x.ToString()).ToArray());
Console.WriteLine(listAsString);
int result = Int32.Parse(listAsString);
Console.WriteLine(result);

You could do it by adding all the numbers in a loop. 你可以通过在循环中添加所有数字来实现。 Not sure it's faster than string parsing though: 不确定它比字符串解析更快:

List<int> list = new List<int> {1, 2, 3};
int sum = 0;
int pow = list.Count - 1;
for (int i = 0; i <= pow; i++)
{
    sum += list[i] * (int)Math.Pow(10,(pow-i));
}

Also if you have a long list, you might want to use .Net 4's BigInteger class instead of an int. 此外,如果您有一个长列表,您可能希望使用.Net 4的BigInteger类而不是int。

Well just for fun (I have no idea how effecient this is, probably not very), you can also do this easily with Linq... 好吧只是为了好玩(我不知道这是多么有效,可能不是很好),你也可以用Linq轻松做到这一点......

first convert the list of ints to a list of strings, then use the aggregate function to concatenate them, then at the end use in32.TryParse to make sure the resulting value is in the int range. 首先将int列表转换为字符串列表,然后使用aggregate函数将它们连接起来,然后在最后使用in32.TryParse来确保结果值在int范围内。

string val = ints.Select(i=> i.ToString()).Aggregate((s1, s2) => s1 + s2);

Say, you have an enumerable like 说,你有一个可以说的数字

var digits = [1, 2, 3 ...];

then you could do: 然后你可以这样做:

// simplest and correct way; essentially the accepted answer but using LINQ
var number = digits.Aggregate((a, b) => a * 10 + b);

// string manipulation; works for sets like [10, 20, 30]
var number = int.Parse(string.Join("", digits));

// using `Select` instead of `Aggregate` but verbose; not very useful
var number = (int)digits.Select((d, i) => d * Math.Pow(10, digits.Count() - i - 1)).Sum();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM