Convert Int List to Integer

This is a bit of a strange case that I have to admit, but I'm trying to find a concise and elegant way to convert a List<int> into an actual 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 to do this would be to convert the array to a string and then parse the string.

Any clues?

+6
c #
source share
6 answers

Iterate over the list, as if adding the amount, but multiply the total by 10 at each step.

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

You will need to make sure that the list is long enough so that the resulting number exceeds the limits for int, though.

+2
source share

I think the suggestion is very 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); 
+1
source share

You can do this by adding all the numbers in the loop. Not sure if this is faster than parsing:

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

Alternatively, if you have a long list, you can use the .Net 4 BigInteger class instead of int.

0
source share

Good only for pleasure (I donโ€™t know how effective it is, maybe not very), you can also do it easily with Linq ...

first convert the int list to a list of strings, then use the aggregate function to concatenate them, and then use in32.TryParse at the end to make sure the resulting value is in the int range.

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

Say you have an enumerated type

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

then you can 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(); 
0
source share

All Articles