Skip to content

Instantly share code, notes, and snippets.

@richardszalay
Last active April 29, 2016 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardszalay/2af891e3bb80f4dd93e763a3b06d6bf2 to your computer and use it in GitHub Desktop.
Save richardszalay/2af891e3bb80f4dd93e763a3b06d6bf2 to your computer and use it in GitHub Desktop.
WhereParsed extension method, combining Where and Select for attempted conversions (like TryParse)
/*
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