1. Creating a List:
To use lists in C#, you need to include the System.Collections.Generic
namespace. Here's how you can create a list:
2. Initialization with Collection Initializer:
You can also initialize a list using a collection initializer:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
3. Accessing Elements:
Access elements by index:
int firstElement = numbers[0];
4. List Methods:
Add
: Adds an element to the end of the list.Remove
: Removes the first occurrence of a specific element.Count
: Gets the number of elements contained in the list.Clear
: Removes all elements from the list.
5. Iterating Through a List:
You can use a foreach
loop or a for
loop to iterate through the elements of a list:
6. Sorting a List:
Use the Sort
method to sort a list:
numbers.Sort();
7. Finding Elements:
Use methods like Contains
, IndexOf
, or Find
to find elements:
8. List of Objects:
Lists can store any type of object. For example:
List<Person> people = new List<Person>(); people.Add(new Person("John", 25));
9. List of Strings:
Lists can be used to store strings as well:
List<string> words = new List<string> { "apple", "banana", "orange" };
10. Conclusion:
Lists in C# are powerful and flexible. They provide a convenient way to work with collections of items. By understanding the basic operations and methods, you can efficiently manipulate and retrieve data from lists in your C# programs.
This tutorial covers the fundamental aspects of working with lists in C#. Depending on your specific use case, you may need to explore additional features and methods provided by the List
class in the C# documentation.