C# List Basics
C# List Basics
can you tell me about c# lists and some common subcommands for c# lists? basically everything I
need to know as a beginner
In C#, a List is a flexible, strongly-typed collection that stores objects of the same type in an ordered
manner. Lists belong to the `System.Collections.Generic` namespace and are part of the generic
collections in C#. Lists are often preferred over arrays because they offer more flexibility (e.g., dynamic
resizing).
Declaring a List
Syntax:
csharp
using System.Collections.Generic;
Example:
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>();
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/5
Here are the most frequently used methods and properties:
1. Adding Elements
csharp
csharp
2. Accessing Elements
csharp
csharp
csharp
3. Modifying Elements
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/5
`Remove(item)`: Removes the first occurrence of the item.
csharp
numbers.Remove(15);
csharp
csharp
numbers.Clear();
csharp
csharp
5. List Properties
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/5
`Capacity`: Gets or sets the total number of elements the internal data structure can hold.
csharp
csharp
numbers.Sort();
csharp
numbers.Reverse();
csharp
csharp
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/5
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a List
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
// Add items
fruits.Add("Date");
fruits.AddRange(new string[] { "Elderberry", "Fig" });
// Remove items
fruits.Remove("Fig");
fruits.RemoveAt(2);
Best Practices
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/5