find the smallest key in a map in csharp

To find the smallest key in a Map (Dictionary) in C#, you can use LINQ to sort the keys and then select the first one:

main.cs
// Create a new Dictionary
Dictionary<int, string> myMap = new Dictionary<int, string>();

// Add some items
myMap.Add(3, "three");
myMap.Add(1, "one");
myMap.Add(2, "two");

// Find the smallest key
int smallestKey = myMap.Keys.OrderBy(k => k).First();

// Output the result
Console.WriteLine("The smallest key is: " + smallestKey);
334 chars
14 lines

In this example, the Dictionary contains three items with keys 3, 1, and 2. The Keys property is used to get a collection of all the keys in the Dictionary. OrderBy() is used to sort them in ascending order. And First() is used to get the first (i.e. smallest) key in the sorted collection. Finally, the result is printed to the console.

gistlibby LogSnag