How do you concatenate Lists in C#?

前端 未结 6 1959
闹比i
闹比i 2020-12-23 13:09

If I have:

List myList1;
List myList2;

myList1 = getMeAList();
// Checked myList1, it contains 4 strings

myList2 = getMeAnother         


        
6条回答
  •  借酒劲吻你
    2020-12-23 13:19

    It also worth noting that Concat works in constant time and in constant memory. For example, the following code

            long boundary = 60000000;
            for (long i = 0; i < boundary; i++)
            {
                list1.Add(i);
                list2.Add(i);
            }
            var listConcat = list1.Concat(list2);
            var list = listConcat.ToList();
            list1.AddRange(list2);
    

    gives the following timing/memory metrics:

    After lists filled mem used: 1048730 KB
    concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
    convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
    list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB
    

提交回复
热议问题