I have a list in C#:
var list = new List();
list.AddRange(GetGreenCars());
list.AddRange(GetBigCars());
list.AddRange(
I created an extension method that adds only unique values to anything implementing ICollection
(including a List
) from an IEnumerable
. Unlike implementations that use List
, this method allows you to specify a lambda expression that determines if two items are the same.
///
/// Adds only items that do not exist in source. May be very slow for large collections and some types of source.
///
/// Type in the collection.
/// Source collection
/// Predicate to determine whether a new item is already in source.
/// New items.
public static void AddUniqueBy(this ICollection source, Func predicate, IEnumerable items)
{
foreach (T item in items)
{
bool existsInSource = source.Where(s => predicate(s, item)).Any();
if (!existsInSource) source.Add(item);
}
}
Usage:
source.AddUniqueBy((s, i) => s.Id == i.Id, items);