Skip to footer content
.NET HELP

C# Sorted List (How it Works for Developers)

Introduction to C# SortedList

What is a SortedList?

The C# SortedList class is a collection of key-value pairs, similar to a dictionary, but it has the added benefit of automatic sorting by keys. It is part of the System.Collections.Generic namespace and is designed for scenarios where you need quick access to sorted data. SortedList<TKey, TValue> is ideal when you need to maintain data in a particular order and access elements efficiently by key.

When working with SortedLists alongside PDF generation tasks, IronPDF integrates perfectly with this class, providing enhanced control over PDF generation.

Key Features and Use Cases

  • Key-Value Pair Storage: Like a dictionary, SortedList stores data as key-value pairs.
  • Automatic Sorting: SortedList keeps associated values sorted by key in ascending order by default.
  • Efficient Data Retrieval: Quick retrieval of associated values by key makes it suitable for lookups.
  • Use Cases: Useful for applications needing sorted data, such as managing ordered lists of names, dates, or numerical values.

How SortedList Works

Data Structure Overview

The public class SortedList is a hybrid between an array and a hash table and organizes its items by key. Internally, it uses a sorted array to keep key values in order, ensuring efficient lookups by key. However, insertion and deletion operations can be slower than in a Dictionary.

Sorting Mechanism

By default, SortedList<TKey, TValue> sorts keys in ascending order using the IComparable interface, which ensures that string keys and other types implement a default comparison behavior. If a custom sorting order is needed, a custom comparer can be provided.

Advantages and Limitations

  • Pros:
    • Fast Key Access: Provides fast O(log n) access by key.
    • Sorted Order: Data is automatically sorted by key without additional sorting overhead.
  • Cons:
    • Insertion Speed: Slower than Dictionary for insertions, especially with large data sizes.
    • Limited Efficiency for Non-Key Operations: Less efficient in scenarios where data isn’t accessed primarily by specific key values.

Working with C# SortedList

Creating a SortedList

You can create a SortedList in C# using either the default constructor or by passing an IComparer if custom sorting is needed. The SortedList has a default initial capacity of 16, which can be adjusted for performance improvements when the approximate size is known.

// Create a SortedList with integer keys and string values
SortedList<int, string> sortedList = new SortedList<int, string>();
// Create a SortedList with integer keys and string values
SortedList<int, string> sortedList = new SortedList<int, string>();
' Create a SortedList with integer keys and string values
Dim sortedList As New SortedList(Of Integer, String)()
$vbLabelText   $csharpLabel

Adding Items

Add key-value pairs to the SortedList using the Add method. This keeps items sorted by key. The following code keeps the SortedList data in ascending order of keys.

sortedList.Add(1, "Apple");
sortedList.Add(3, "Banana");
sortedList.Add(2, "Cherry");
sortedList.Add(1, "Apple");
sortedList.Add(3, "Banana");
sortedList.Add(2, "Cherry");
sortedList.Add(1, "Apple")
sortedList.Add(3, "Banana")
sortedList.Add(2, "Cherry")
$vbLabelText   $csharpLabel

Accessing and Modifying Elements

Access elements in a SortedList by their keys. You can retrieve or modify values associated with keys directly.

// Accessing a specific value by key
string value = sortedList[1];  // Retrieves "Apple"
// Modifying a value
sortedList[1] = "Avocado";   // Changes the value associated with key 1 to "Avocado"
// Accessing a specific value by key
string value = sortedList[1];  // Retrieves "Apple"
// Modifying a value
sortedList[1] = "Avocado";   // Changes the value associated with key 1 to "Avocado"
' Accessing a specific value by key
Dim value As String = sortedList(1) ' Retrieves "Apple"
' Modifying a value
sortedList(1) = "Avocado" ' Changes the value associated with key 1 to "Avocado"
$vbLabelText   $csharpLabel

Removing Items

Remove items using specific keys with the Remove method or using the specified index with RemoveAt. Both allow controlled deletion of objects from the SortedList.

sortedList.Remove(3);       // Removes the entry with key 3
sortedList.RemoveAt(0);     // Removes the entry at the zero-based index 0
sortedList.Remove(3);       // Removes the entry with key 3
sortedList.RemoveAt(0);     // Removes the entry at the zero-based index 0
sortedList.Remove(3) ' Removes the entry with key 3
sortedList.RemoveAt(0) ' Removes the entry at the zero-based index 0
$vbLabelText   $csharpLabel

Iterating Over a SortedList

Iterate over SortedList using a foreach loop to retrieve both keys and values in sorted order.

foreach (KeyValuePair<int, string> kvp in sortedList)
{
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
foreach (KeyValuePair<int, string> kvp in sortedList)
{
    Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
For Each kvp As KeyValuePair(Of Integer, String) In sortedList
	Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
Next kvp
$vbLabelText   $csharpLabel

C# Sorted List (How it Works for Developers): Figure 1

Practical Examples of Using SortedList

  • Example 1: Storing and retrieving data in a simple key-value format where order matters, such as student names by their roll numbers.
  • Example 2: Using SortedList in more complex scenarios, such as displaying sorted transaction logs or ranked scores.

Best Practices:

  • Use SortedList when keys are the primary access point and need to remain sorted.
  • For frequent insertions, consider alternatives like SortedDictionary for better performance.

Performance Considerations

Comparing SortedList with Dictionary and List

  • SortedList vs. Dictionary: SortedList is slower for insertions compared to Dictionary due to sorting overhead.
  • SortedList vs. List: Unlike a list, SortedList is designed for accessing elements by key and maintaining sorted order.

When to Use SortedList: Use it when you need sorted data and primarily access it by key, especially for read-heavy scenarios.

Integration with IronPDF for PDF Export

Introduction to IronPDF

C# Sorted List (How it Works for Developers): Figure 2

IronPDF is a powerful library for generating and modifying PDF files in C#. It allows developers to create PDFs from various sources, add content programmatically, and customize PDF layouts. In this section, we’ll use IronPDF to create a PDF report from SortedList data.

Generating PDF Reports from SortedList Data

To begin using IronPDF, install the IronPDF NuGet package:

Install-Package IronPdf

Example: Exporting Data from a SortedList to a PDF

The following example demonstrates how to export data from a SortedList to a PDF table.

First, set up your SortedList:

SortedList<int, string> sortedList = new SortedList<int, string>
{
    { 1, "Apple" },
    { 2, "Banana" },
    { 3, "Cherry" }
};
SortedList<int, string> sortedList = new SortedList<int, string>
{
    { 1, "Apple" },
    { 2, "Banana" },
    { 3, "Cherry" }
};
Dim sortedList As New SortedList(Of Integer, String) From {
	{1, "Apple"},
	{2, "Banana"},
	{3, "Cherry"}
}
$vbLabelText   $csharpLabel

Next, use IronPDF to generate a PDF from this data:

// Initialize a PDF renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Build HTML string with table format
string html = "<h1>Sorted List Data</h1><table border='1'><tr><th>Key</th><th>Value</th></tr>";
foreach (var kvp in sortedList)
{
    html += $"<tr><td>{kvp.Key}</td><td>{kvp.Value}</td></tr>";
}
html += "</table>";

// Render HTML to PDF and save it
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("sortedList.pdf");
// Initialize a PDF renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Build HTML string with table format
string html = "<h1>Sorted List Data</h1><table border='1'><tr><th>Key</th><th>Value</th></tr>";
foreach (var kvp in sortedList)
{
    html += $"<tr><td>{kvp.Key}</td><td>{kvp.Value}</td></tr>";
}
html += "</table>";

// Render HTML to PDF and save it
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("sortedList.pdf");
' Initialize a PDF renderer
Dim renderer As New ChromePdfRenderer()

' Build HTML string with table format
Dim html As String = "<h1>Sorted List Data</h1><table border='1'><tr><th>Key</th><th>Value</th></tr>"
For Each kvp In sortedList
	html &= $"<tr><td>{kvp.Key}</td><td>{kvp.Value}</td></tr>"
Next kvp
html &= "</table>"

' Render HTML to PDF and save it
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("sortedList.pdf")
$vbLabelText   $csharpLabel

C# Sorted List (How it Works for Developers): Figure 3

This code creates an HTML table from the SortedList data and converts it into a PDF using IronPDF.

Advanced Features

  • Customizing PDF Layout: IronPDF allows CSS styling for layouts, fonts, colors, etc.
  • Headers and Footers: IronPDF supports headers and footers, which can include page numbers or logos.

Summary and Best Practices

  • SortedList Overview: SortedList is a sorted key-value collection, best for scenarios where data is accessed by specific keys and needs to remain sorted.
  • Using IronPDF for Exporting: IronPDF is a convenient library for exporting SortedList data to PDFs, supporting custom layouts and styling.

Conclusion

In this article, we explored the C# SortedList class, a powerful tool for managing sorted, key-value data collections. SortedList is especially useful in scenarios where order and efficient access by key are critical. From creating, adding, and removing elements to integrating with IronPDF for PDF export, we covered practical steps and best practices for using SortedList in real-world applications.

Additionally, we showcased how IronPDF can simplify the task of exporting specified values from a SortedList to PDF format, allowing for the easy creation of professional, well-organized reports. IronPDF’s versatility, including customizable headers, footers, and CSS styling, makes it an excellent choice for generating PDFs directly from your C# applications.

If you’re interested in trying IronPDF, it offers a free trial that allows you to explore its full range of features without commitment. This trial enables testing of PDF generation, customization options, and integration into existing projects to ensure it meets your needs. By combining SortedList and IronPDF, developers gain a robust, efficient solution for managing and reporting sorted data in C# applications.

Frequently Asked Questions

What is a C# SortedList?

The C# SortedList class is a collection of key-value pairs that automatically sorts keys. It is part of the System.Collections.Generic namespace and is used for scenarios requiring quick access to sorted data.

How does a SortedList differ from a Dictionary in C#?

While both SortedList and Dictionary store data as key-value pairs, SortedList automatically sorts data by key, whereas Dictionary does not maintain any order.

What are the benefits of using a SortedList?

SortedList offers fast O(log n) access by key, maintains data in sorted order, and provides efficient data retrieval by key.

What are the limitations of a SortedList?

SortedList can be slower than a Dictionary for insertions and deletions, especially with large data sizes, and is less efficient for operations not primarily based on key access.

How do you create a SortedList in C#?

You can create a SortedList using the default constructor or by passing an IComparer for custom sorting. For example: SortedListsortedList = new SortedList();

How can items be added to a SortedList?

Items can be added to a SortedList using the Add method, which keeps the items sorted by key.

How can sorted key-value data be exported as a PDF?

IronPDF can be used to generate PDF reports from SortedList data, allowing developers to create PDFs from sorted key-value data collections.

When should you use a SortedList over a Dictionary?

Use a SortedList when you need sorted data and primarily access it by key, especially in read-heavy scenarios.

What are some practical examples of using a SortedList?

Practical examples include storing student names by roll numbers in order or displaying sorted transaction logs.

What is the default sorting order in a SortedList?

By default, a SortedList sorts keys in ascending order using the IComparable interface.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.