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

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

I have a list in C#:

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


        
9条回答
  •  旧时难觅i
    2021-01-07 16:47

    Linq-less option! A different option in case the programmer cannot, or don't wanna use Linq.

    var list = new List();
    list.AddRange(GetGreenCars().FindAll((x) => !list.Contains(x)));
    list.AddRange(GetBigCars().FindAll((x) => !list.Contains(x)));
    list.AddRange(GetSmallCars().FindAll((x) => !list.Contains(x)));
    

    If the initial list is empty as in the example above, you can actually avoid using FindAll(...) on the first AddRange().

提交回复
热议问题