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

前端 未结 9 1513
[愿得一人]
[愿得一人] 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 17:03

    Another option is to do something like:

    public static void AddUnique( this IList self, IEnumerable items )
    {
        foreach(var item in items)
            if(!self.Contains(item))
                self.Add(item);
    }
    
    
    var list = new List();
    list.AddUnique(GetGreenCars());
    list.AddUnique(GetBigCars());
    list.AddUnique(GetSmallCars());
    

提交回复
热议问题