AddRange to a Collection

后端 未结 8 2204
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 11:41

A coworker asked me today how to add a range to a collection. He has a class that inherits from Collection. There\'s a get-only property of that type t

8条回答
  •  眼角桃花
    2020-12-01 12:10

    Since .NET4.5 if you want one-liner you can use System.Collections.Generic ForEach.

    source.ForEach(o => destination.Add(o));
    

    or even shorter as

    source.ForEach(destination.Add);
    

    Performance-wise it's the same as for each loop (syntactic sugar).

    Also don't try assigning it like

    var x = source.ForEach(destination.Add) 
    

    cause ForEach is void.

    Edit: Copied from comments, Lipert's opinion on ForEach

提交回复
热议问题