Add elements from one list to another C#

前端 未结 2 787
长发绾君心
长发绾君心 2021-02-18 21:58

What is the simplest way to add elements of one list to another?

For example, I have two lists:

List A which contains x items List B which contains y items.

2条回答
  •  无人共我
    2021-02-18 22:00

    Your question describes the List.AddRange method, which copies all the elements of its argument into the list object on which it is called.

    As an example, the snippet

    List listA = Enumerable.Range(0, 10).ToList();
    List listB = Enumerable.Range(11, 10).ToList();
    Console.WriteLine("Old listA: [{0}]", string.Join(", ", listA));
    Console.WriteLine("Old listB: [{0}]", string.Join(", ", listB));
    listA.AddRange(listB);
    Console.WriteLine("New listA: [{0}]", string.Join(", ", listA));
    

    prints

    Old listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    Old listB: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    New listA: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    

    showing that all the elements of listB were added to listA in the AddRange call.

提交回复
热议问题