List Method Cheat-Sheet

Md Asif AlamMd Asif Alam
3 min read

Here's a cheat sheet for common methods and operations on List in C#:

Creating and Initializing Lists

List<int> numbers = new List<int>(); // Empty list
List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; // Initialized with elements

Adding Elements

numbers.Add(10); // Adds a single item
numbers.AddRange(new int[] { 20, 30, 40 }); // Adds a collection of items

Accessing Elements

int firstNumber = numbers[0]; // Access by index
int lastNumber = numbers[numbers.Count - 1]; // Last element

Removing Elements

numbers.Remove(20); // Removes the first occurrence of 20
numbers.RemoveAt(0); // Removes element at index 0
numbers.RemoveAll(n => n > 30); // Removes all elements matching the condition
numbers.Clear(); // Removes all elements from the list

Checking Existence

bool containsBob = names.Contains("Bob");
int index = names.IndexOf("Charlie"); // Returns index of first occurrence or -1 if not found

Sorting and Reversing

numbers.Sort(); // Sorts the list
numbers.Reverse(); // Reverses the list

Iterating Through List

foreach (var name in names)
{
    Console.WriteLine(name);
}

List Information

int count = numbers.Count; // Number of elements in the list
bool isEmpty = numbers.Count == 0; // Checks if list is empty

Converting to Array

int[] numbersArray = numbers.ToArray(); // Converts list to array

Finding Elements

List<string> results = names.FindAll(name => name.Length > 4); // Finds all elements matching the condition
string foundName = names.Find(name => name.StartsWith("A")); // Finds first element matching the condition

Copying and Cloning

List<int> copy = new List<int>(numbers); // Copies the list
List<int> clone = numbers.ToList(); // Clones the list

These are some of the most commonly used methods and operations on List in C#. They should cover a wide range of scenarios for manipulating and working with lists effectively.

Of course! Here are some additional operations and methods you might find useful when working with List in C#:

Inserting and Removing Range

numbers.Insert(2, 25); // Inserts 25 at index 2, shifting subsequent elements
numbers.InsertRange(1, new int[] { 15, 20 }); // Inserts a collection starting at index 1
numbers.RemoveRange(3, 2); // Removes 2 elements starting from index 3

Checking and Modifying List

numbers.Exists(n => n > 50); // Checks if any element satisfies the condition
numbers.TrueForAll(n => n > 0); // Checks if all elements satisfy the condition
numbers.ConvertAll(n => n.ToString()); // Converts all elements to another type

Range Operations

List<int> subList = numbers.GetRange(1, 3); // Gets elements from index 1 to 3 (exclusive)

Sorting with Comparer

numbers.Sort((x, y) => y.CompareTo(x)); // Custom sorting with a comparer
numbers.Sort();
int index = numbers.BinarySearch(30); // Performs binary search, requires sorted list

Checking Subsets

List<int> subset = new List<int> { 20, 30 };
bool isSubset = subset.All(item => numbers.Contains(item)); // Checks if subset exists in numbers

LINQ Integration

using System.Linq;

var sortedNumbers = numbers.OrderBy(n => n); // Sorting using LINQ
var filteredNames = names.Where(name => name.Length > 4); // Filtering using LINQ

Synchronizing Access

List<int> synchronizedList = List.Synchronized(numbers); // Creates a thread-safe wrapper

List Capacity Management

numbers.Capacity = 50; // Adjusts the capacity of the list
numbers.TrimExcess(); // Reduces the capacity to match the count

Enumeration

IEnumerator<int> enumerator = numbers.GetEnumerator();
while (enumerator.MoveNext())
{
    int current = enumerator.Current;
    // Do something with current element
}

These additional operations should cover a broad range of functionalities and scenarios when working with lists in C#. They provide flexibility and efficiency for managing collections of elements in your applications.

0
Subscribe to my newsletter

Read articles from Md Asif Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md Asif Alam
Md Asif Alam

๐Ÿš€ Full Stack .NET Developer & React Enthusiast ๐Ÿ‘จโ€๐Ÿ’ป About Me: With 3+ years of experience, I'm passionate about crafting robust solutions and seamless user experiences through code. ๐Ÿ’ผ Expertise: Proficient in .NET Core API, ASP.NET MVC, React.js, and SQL. Skilled in backend architecture, RESTful APIs, and frontend development. ๐ŸŒŸ Achievements: Led projects enhancing scalability by 50%, delivered ahead of schedule, and contributed to open-source initiatives. ๐Ÿ” Future Focus: Eager to embrace new technologies and drive innovation in software development. ๐Ÿ“ซ Let's Connect: Open to new opportunities and collaborations. Reach me on LinkedIn or GitHub!