DEV Community

Discussion on: Your favorite/most useful extension methods?

Collapse
 
jastbytes profile image
Jan Steffen

Hey there,

pretty handy extension. I've a library with many extension methods myself on github.com/iss0/jastExtensions. I have some methods which somehow solve the same problem, but afterwards cleaning up the list or dictionary:

/// <summary>
/// Removes all elements from the collection which are null 
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw new ArgumentNullException(nameof(source));
    }

    return source.Where(t => t != null);
}

/// <summary>
/// Removes every entry from the dictionary whose value is null
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dictionary"></param>
/// <returns></returns>
public static IDictionary<TKey, TValue> ValueNotNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
    if (dictionary == null)
    {
        throw new ArgumentNullException(nameof(dictionary));
    }

    return dictionary.Where(pair => pair.Value != null).ToDictionary(pair => pair.Key, pair => pair.Value);
}

These two methods are just a few I've found useful over time and are part of my library. Some limitations on extension methods will fall in future C# 8, see channel9.msdn.com/Blogs/Seth-Juare....