Can I write these functions more efficient?
public static void AddDistinct<T>(this ICollection<T> source, params ICollection<T>[] collections)
{
(from collection in collections from item in collection where !source.Contains(item) select item).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params ICollection<T>[] collections)
{
collections.ForEach(collection => collection.Where(predicate).Where(item => !source.Contains(item)).ForEach(source.Add));
}
public static void AddDistinct<T>(this ICollection<T> source, params T[] items)
{
items.Where(item => !source.Contains(item)).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params T[] items)
{
items.Where(predicate).Where(x => !source.Contains(x)).ForEach(source.Add);
}
You can use the
Exceptmethod:Note that because
WhereandExcepthave deferred and streamed execution, you need theToArray()call to ensure the enumeration ofsourceis complete before you add anything to it (since a collection can’t be modified while it’s being enumerated).