c# list array
时间: 2023-08-26 22:05:44 浏览: 109
C# provides two main data structures for storing collections of elements: List and Array. Both List and Array are used to store and manipulate a collection of items, but they have some differences in terms of flexibility and functionality.
An Array is a fixed-size collection of elements of the same type. Once an array is created, its size cannot be changed. You need to specify the size of the array when declaring it. Array elements can be accessed using an index, starting from 0.
Here's an example of creating and accessing elements in an array:
```csharp
int[] numbers = new int[5]; // Creating an array of size 5
numbers[0] = 1; // Accessing and setting the value at index 0
int firstNumber = numbers[0]; // Accessing the value at index 0
```
On the other hand, List is a dynamic collection that can grow or shrink in size. It allows adding, removing, and modifying elements easily. List provides several methods and properties to manipulate the collection efficiently.
Here's an example of creating and manipulating elements in a List:
```csharp
List<int> numbers = new List<int>(); // Creating an empty list
numbers.Add(1); // Adding an element to the list
int firstNumber = numbers[0]; // Accessing the value at index 0
numbers.Remove(1); // Removing an element from the list
```
In summary, Arrays have a fixed size, while Lists can dynamically grow or shrink. Arrays are generally more efficient in terms of memory, but Lists provide more flexibility and functionality for manipulating collections.
阅读全文