Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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