Last active
January 7, 2026 21:52
-
-
Save amirrajan/342b88edd9edb26db2a72b4616bf6dfc to your computer and use it in GitHub Desktop.
.ToInt extension method
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; | |
| using System.Collections.Generic; | |
| using static Sugar; | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| if ("1111".ToInt() is int parsed) | |
| { | |
| Console.WriteLine(parsed); | |
| } | |
| int result = "2222".ToInt() ?? 0; | |
| Console.WriteLine(result); | |
| var maybeNumbers = List("AAA", "111", "NOPE", "333", "YOOOOO", "012311"); | |
| maybeNumbers.Select(s => s.ToInt()) | |
| .Compact() | |
| .ForEach(f => Console.WriteLine(f)); | |
| } | |
| } | |
| public static class Sugar | |
| { | |
| public static int? ToInt(this string n) | |
| { | |
| int result = 0; | |
| if (int.TryParse(n, out result)) return result; | |
| else return null; | |
| } | |
| public static IEnumerable<T> Compact<T>(this IEnumerable<T> os) | |
| { | |
| return os.Where(os => os is not null); | |
| } | |
| public static void ForEach<T>(this IEnumerable<T> os, Action<T> action) | |
| { | |
| foreach(var o in os) action(o); | |
| } | |
| public static List<T> List<T>(T item, params T[] rest) | |
| { | |
| var list = new List<T> { item }; | |
| list.AddRange(rest); | |
| return list; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment