Add elements from one list to another C#

前端 未结 2 795
长发绾君心
长发绾君心 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:23

    To join two lists, you can do

    listA.AddRange(listB); // listA will contain x+y items
    

    or

    // listC contains x+y items, listA and listB are unchanged.
    var listC = listA.Concat(listB); 
    

    You could use the latter to reassign listA instead:

    listA = listA.Concat(listB).ToList();
    

    but there isn't any particular advantage to that over AddRange if you're okay with modifying one of the original lists in the first place.

提交回复
热议问题