Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Created November 7, 2015 01:24
Show Gist options
  • Save taisyo7333/a5eb1dac29dbf0eca6a8 to your computer and use it in GitHub Desktop.
Save taisyo7333/a5eb1dac29dbf0eca6a8 to your computer and use it in GitHub Desktop.
[C#] 整数で構成される文字列をint型に変換する.(Parseを使用せずにLINQを使用してみる)
using System;
using System.Linq;
namespace ParseInt
{
class Program
{
static void Main(string[] args)
{
// Success
int n = ParseInt("123");
// throw exception
ParseInt("12f");
}
static int ParseInt(string s)
{
if (true != s.All(e => char.IsDigit(e)))
throw new ArgumentOutOfRangeException("s", "Param s should be only '0' - '9'");
return s.Select(e => (int)e - 0x30).Aggregate((fold, e) => fold = fold * 10 + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment