ExtensionMethod.NET Home of 827 C#, Visual Basic, F# and Javascript extension methods

AddIf

Extension that adds an element to a collection only if a given condition is met. Same as if (some condition) collection.Add(element)

Source

public static class CollectionExtensions
{
    public static void AddIf<T>(this ICollection<T> collection, Func<bool> predicate, T item)
    {
        if (predicate.Invoke())
            collection.Add(item);
    }

    public static void AddIf<T>(this ICollection<T> collection, Func<T, bool> predicate, T item)
    {
        if (predicate.Invoke(item))
            collection.Add(item);
    }

}

Example

//Generic condition
People.AddIf(() => TodayIsFraiday() , person);

//Item specific condition
People.AddIf(p => p.Age >= 8, person);

Author: Txaran Rodriguez

Submitted on: 6 mei 2020

Language: csharp

Type: ICollection

Views: 123