Is there an AddUnique method similar to Addrange() for alist in C#

前端 未结 9 1512
[愿得一人]
[愿得一人] 2021-01-07 16:32

I have a list in C#:

       var list = new List();
       list.AddRange(GetGreenCars());
       list.AddRange(GetBigCars());
       list.AddRange(         


        
9条回答
  •  被撕碎了的回忆
    2021-01-07 16:49

    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.Contains(), 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);
    

提交回复
热议问题