Created
November 7, 2015 01:24
-
-
Save taisyo7333/a5eb1dac29dbf0eca6a8 to your computer and use it in GitHub Desktop.
[C#] 整数で構成される文字列をint型に変換する.(Parseを使用せずにLINQを使用してみる)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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