Last active
April 29, 2016 05:42
-
-
Save richardszalay/2af891e3bb80f4dd93e763a3b06d6bf2 to your computer and use it in GitHub Desktop.
WhereParsed extension method, combining Where and Select for attempted conversions (like TryParse)
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
/* | |
Usage: "1,2,c,4".Split(',').WhereParsed<int>(int.TryParse) | |
*/ | |
public delegate bool TryConversion<TIn, TOut>(TIn input, out TOut output); | |
public static class WhereConvertedExtensions | |
{ | |
/// <summary> | |
/// Filters an enumerable to elements that succeeded in conversion via a "Try*" pattern implementation | |
/// </summary> | |
public static IEnumerable<TOut> WhereConverted<TIn, TOut>(this IEnumerable<TIn> source, TryConversion<TIn, TOut> conversion) | |
{ | |
foreach (TIn value in source) | |
{ | |
TOut converted; | |
if (conversion(value, out converted)) | |
yield return converted; | |
} | |
} | |
/// <summary> | |
/// Filters an enumerable to elements that succeeded in conversion via a "TryParse" pattern implementation | |
/// </summary> | |
public static IEnumerable<TOut> WhereParsed<TOut>(this IEnumerable<string> source, TryConversion<string, TOut> conversion) | |
{ | |
return source.WhereConverted(conversion); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment