📅  最后修改于: 2023-12-03 15:30:17.930000             🧑  作者: Mango
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 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.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.
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.