Elegant way to combine multiple collections of elements?

前端 未结 11 2379
再見小時候
再見小時候 2020-12-05 03:36

Say I have an arbitrary number of collections, each containing objects of the same type (for example, List foo and List bar).

11条回答
  •  一向
    一向 (楼主)
    2020-12-05 04:25

    All you need is this, for any IEnumerable> lists :

    var combined = lists.Aggregate((l1, l2) => l1.Concat(l2));
    

    This will combine all the items in lists into one IEnumerable (with duplicates). Use Union instead of Concat to remove duplicates, as noted in the other answers.

提交回复
热议问题