4 ms·
@Bogdanp maybe this is another way to express it: public static class EnumerableExtensions { public static IEnumerable<TR> SelectNotNull<T, TR>( this IEnu
by manuc66 1y ago
@Bogdanp maybe this is another way to express it:
public static class EnumerableExtensions
{
public static IEnumerable<TR> SelectNotNull<T, TR>(
this IEnumerable<T> source,
Func<T, TR?> fn)
where TR : class
{
return source.Select(fn)
.Where(it => it != null)
.OfType<T>();
}
public static IEnumerable<TR> SelectNotNull<T, TR>(
this IEnumerable<T> source,
Func<T, TR?> fn)
where TR : struct
{
return source.Select(fn)
.Where(it => it != null)
.Select(item => item.Value);
}
}
- Uvix 1y agoBoth look like they’ll work. For the struct case I think yours is better. For the class case I think using Cast() like the original instead of OfType() makes more sense - you don’t need to filter out other types from the enumerable, so cast once instead of casting then performing a useless check on the result.
- nick_ 1y agoI'm pretty sure you only need the OfType call. It filters out nulls already.