From 1763d1773a7238b2282c399865857ba3dbeb7c2f Mon Sep 17 00:00:00 2001 From: Jeffery Thompson Date: Fri, 30 Mar 2018 15:47:46 -0400 Subject: [PATCH] feat: add TryParseSkipFailures extension --- .../Extensions/EnumerableExtensions.cs | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs index 5233bd5..3bc0fd4 100644 --- a/ICD.Common.Utils/Extensions/EnumerableExtensions.cs +++ b/ICD.Common.Utils/Extensions/EnumerableExtensions.cs @@ -1057,6 +1057,40 @@ namespace ICD.Common.Utils.Extensions } } + // since S# can't do anonymous types + private struct TryParseStruct + { + public readonly T value; + public readonly bool isParsed; + public TryParseStruct(T value, bool isParsed) + { + this.value = value; + this.isParsed = isParsed; + } + } + // since Func<...,T> can't specify `out` parameters + public delegate bool TryParseDelegate(string input, out T output); + + /// + /// Attempts to parse each value of the enumerable, + /// throwing away the values that don't parse correctly. + /// + /// type to parse to + /// enumerable of strings to parse + /// TryParse function for given type + /// enumerable of successfully parsed values + public static IEnumerable TryParseSkipFailures(this IEnumerable extends, TryParseDelegate tryParseFunc) + { + return extends.Select(str => + { + T value = default(T); + bool isParsed = tryParseFunc(str, out value); + return new TryParseStruct(value, isParsed); + }) + .Where(v => v.isParsed == true) + .Select(v => v.value); + } + #if SIMPLSHARP /// @@ -1093,5 +1127,5 @@ namespace ICD.Common.Utils.Extensions } #endif - } + } }