Reputation: 18220
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
. 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.
Any hints?
Upvotes: 7
Views: 18636
Reputation: 73163
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();
Upvotes: 2
Reputation: 72840
Iterate the list, as if adding a sum, but multiply the running total by 10 at each stage.
int total = 0;
foreach (int entry in list)
{
total = 10 * total + entry;
}
Upvotes: 17
Reputation: 18815
Well just for fun (I have no idea how effecient this is, probably not very), you can also do this easily with 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.
string val = ints.Select(i=> i.ToString()).Aggregate((s1, s2) => s1 + s2);
Upvotes: 0
Reputation: 54999
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.
Upvotes: 4
Reputation: 39697
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.
Upvotes: 0
Reputation: 10291
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);
Upvotes: 1