📌  相关文章
📜  C#|将指定集合的元素添加到列表的末尾(1)

📅  最后修改于: 2023-12-03 15:30:17.930000             🧑  作者: Mango

Introduction to Adding Elements from a Collection to the End of a List in C#

In C#, a List is a data structure that allows you to store and manipulate a collection of elements of any type. You can add elements to a List using the Add method, which adds a single element to the end of the list. However, if you have a collection of elements that you want to add to a List, you may find the AddRange method more useful.

The AddRange Method

The AddRange method allows you to add the elements from a collection to the end of a List. The syntax for using the AddRange method is:

myList.AddRange(myCollection);
  • myList is the List to which you want to add elements.
  • myCollection is the collection from which you want to add elements.
Example

Let's say you have a List of integers and a HashSet of integers, and you want to add the elements from the HashSet to the end of the List. Here's how you could do it:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> myList = new List<int>() { 1, 2, 3 };
        HashSet<int> mySet = new HashSet<int>() { 4, 5, 6 };

        myList.AddRange(mySet);

        foreach (int element in myList)
        {
            Console.WriteLine(element);
        }
    }
}

Output:

1
2
3
4
5
6

In this example, we create a List and a HashSet of integers. We then use the AddRange method to add the elements from the HashSet to the end of the List. Finally, we use a foreach loop to print out each element of the List, which now contains all the elements from the HashSet.

Conclusion

The AddRange method is a useful tool for adding elements from a collection to the end of a List in C#. By using this method, you can quickly and easily combine two collections of elements into one List.