Elegant way to combine multiple collections of elements?

前端 未结 11 2394
再見小時候
再見小時候 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:30

    The only way I see is to use Concat()

     var foo = new List { 1, 2, 3 };
     var bar = new List { 4, 5, 6 };
     var tor = new List { 7, 8, 9 };
    
     var result = foo.Concat(bar).Concat(tor);
    

    But you should decide what is better:

    var result = Combine(foo, bar, tor);
    

    or

    var result = foo.Concat(bar).Concat(tor);
    

    One point why Concat() will be a better choice is that it will be more obvious for another developer. More readable and simple.

提交回复
热议问题