To sort a dictionary by keys in C#, you can use the `OrderBy` method from the `System.Linq` namespace and convert the sorted result back to a dictionary using the `ToDictionary` method. This allows you to create a new dictionary with the key-value pairs sorted by key.
We can sort a dictionary by keys in C# using the `OrderBy` method from the `System.Linq` namespace. This example demonstrates how to declare and initialize a dictionary, use the `OrderBy` method to sort the dictionary by keys, and print the sorted dictionary.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
// Sort the dictionary by keys using OrderBy
Dictionary<int, string> sortedDict = myDictionary
.OrderBy(kvp => kvp.Key)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Print the sorted dictionary
Console.WriteLine("Sorted dictionary:");
foreach (var kvp in sortedDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Sorted dictionary: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three
We can sort a dictionary by keys in descending order in C# using the `OrderByDescending` method from the `System.Linq` namespace. This example demonstrates how to declare and initialize a dictionary, use the `OrderByDescending` method to sort the dictionary by keys in descending order, and print the sorted dictionary.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{3, "Three"},
{1, "One"},
{2, "Two"}
};
// Sort the dictionary by keys in descending order using OrderByDescending
Dictionary<int, string> sortedDict = myDictionary
.OrderByDescending(kvp => kvp.Key)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Print the sorted dictionary
Console.WriteLine("Sorted dictionary:");
foreach (var kvp in sortedDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Sorted dictionary: Key: 3, Value: Three Key: 2, Value: Two Key: 1, Value: One
In this tutorial, we learned How to Sort a Dictionary by Keys in C# language with well detailed examples.