Elegant way to combine multiple collections of elements?

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

    Use Enumerable.Concact:

    var query = foo.Concat(bar);
    
    0 讨论(0)
  • 2020-12-05 04:28

    Use Enumerable.Concat like so:

    var combined = foo.Concat(bar).Concat(baz)....;
    
    0 讨论(0)
  • 2020-12-05 04:29

    A couple techniques using Collection Initializers --

    assuming these lists:

    var list1 = new List<int> { 1, 2, 3 };
    var list2 = new List<int> { 4, 5, 6 };
    

    SelectMany with an array initializer (not really that elegant to me, but doesn't rely on any helper function):

    var combined = new []{ list1, list2 }.SelectMany(x => x);
    

    Define a list extension for Add which allows IEnumerable<T> in the List<T> initializer:

    public static class CollectionExtensions
    {
        public static void Add<T>(this ICollection<T> collection, IEnumerable<T> items)
        {
            foreach (var item in items) collection.Add(item);
        }
    }
    

    Then you can create a new list containing the elements of the others like this (it also allows single items to be mixed in).

    var combined = new List<int> { list1, list2, 7, 8 };
    
    0 讨论(0)
  • 2020-12-05 04:30

    You could always use Aggregate combined with Concat...

            var listOfLists = new List<List<int>>
            {
                new List<int> {1, 2, 3, 4},
                new List<int> {5, 6, 7, 8},
                new List<int> {9, 10}
            };
    
            IEnumerable<int> combined = new List<int>();
            combined = listOfLists.Aggregate(combined, (current, list) => current.Concat(list)).ToList();
    
    0 讨论(0)
  • 2020-12-05 04:30

    The only way I see is to use Concat()

     var foo = new List<int> { 1, 2, 3 };
     var bar = new List<int> { 4, 5, 6 };
     var tor = new List<int> { 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.

    0 讨论(0)
提交回复
热议问题