How to use a list of tuples in C#
By FoxLearn 3/5/2025 4:03:20 AM 32
Creating a List of Tuples
You can create a list of tuples by specifying the types for each element in the tuple and using the List<(T1, T2)>
syntax.
For example, if you want to store a list of books with their titles and authors, you can create a list of tuples like this:
var books = new List<(string title, string author)>() { ("1984", "George Orwell"), ("To Kill a Mockingbird", "Harper Lee"), ("Moby Dick", "Herman Melville") }; foreach (var book in books) { Console.WriteLine($"{book.title} by {book.author}"); }
This creates a list of named tuples (string, string)
where each tuple represents a book’s title and its author. The foreach
loop prints each book's title and author. I recommend using named value tuples rather than System.Tuple
.
Accessing Tuple Elements
You can loop through the list of tuples and access each tuple's elements by their names (if named) or by their positions (index).
foreach (var book in books) { Console.WriteLine($"Title: {book.title}, Author: {book.author}"); }
Adding Tuples to the List
You can add tuples to the list in two ways:
- Using the list initializer syntax when creating the list.
- Using the
Add()
method to add a new tuple to the list.
For example, Using Add()
Method:
books.Add(("Pride and Prejudice", "Jane Austen"));
For example, Adding during initialization:
var moreBooks = new List<(string title, string author)> { ("The Great Gatsby", "F. Scott Fitzgerald") };
When you add a tuple, the field types must match the list’s tuple types in this case, (string, string)
.
Sorting a List of Tuples
You can sort a list of tuples using LINQ or the Sort()
method.
Sorting with LINQ:
To sort a list of tuples, you can use OrderBy()
from LINQ. This lets you easily specify which tuple field to sort by.
using System.Linq; var sortedBooks = books.OrderBy(book => book.title).ToList(); foreach (var book in sortedBooks) { Console.WriteLine($"{book.title} by {book.author}"); }
You can also use OrderByDescending()
to sort in descending order.
In-place sorting using List.Sort()
:
If you want to sort the list in-place (i.e., modify the original list), you can use List.Sort()
with a comparison lambda:
books.Sort((a, b) => a.title.CompareTo(b.title));
If you don’t pass any parameters to List.Sort()
, it uses ValueTuple.CompareTo()
, which sorts based on the order in which the fields are declared in the tuple. This is helpful when sorting by all fields.
Using List of Tuples with Different Types
You can use tuples with different types, such as a list of tuples containing a string and an integer, to represent items like movies or products.
var movies = new List<(string title, int releaseYear)>() { ("The Matrix", 1999), ("Star Wars: A New Hope", 1977), ("Inception", 2010) }; foreach (var movie in movies) { Console.WriteLine($"{movie.title} was released in {movie.releaseYear}"); }
Using Tuple Deconstruction
Tuple deconstruction allows you to extract values from a tuple directly into variables.
foreach (var (title, author) in books) { Console.WriteLine($"Title: {title}, Author: {author}"); }
Using named tuples (e.g., (string title, string author)
) instead of regular tuples (e.g., (string, string)
) makes your code more readable and maintainable because it explicitly names the fields.
- How to Parser a CSV file in C#
- How to read configuration from appsettings.json in C#
- How to Programmatically Update appsettings.json in C#
- How to deconstruct an object in C#
- Handling CSV Files Without a Header Row Using CsvHelper
- CSVHelper: Header with name not found
- How to Convert a Comma-Separated String into a List of Integers in C#
- How to send synchronous requests with HttpClient in C#