Adam Weitzman Adam Weitzman - 1 month ago 10
C# Question

Long from List of Characters C#

I have a list of characters

[5, 1, 3]
what is the best way to convert this list to a long like
513
when I do this:

long.Parse(charList.ToArray().ToString());


I get:


System.FormatException

Answer

The reason you get a FormatException is that the ToArray().ToString()'s output is "System.Char[]" - which is obviously not a float :)

Use string.Join:

long.Parse(string.Join("",charList))

Use long.TryParse if there is a risk for non numeric items and use char.IsNumber if you want to keep only numeric items:

char[] charList = new char[] { '5', '1', '3' };
string.Join("", charList.Where(c => char.IsNumber(c)));
Comments