find the largest key in a map in csharp

To find the largest key in a Dictionary (which is a type of map) in C#, you can use LINQ to sort the keys and select the last one:

main.cs
using System.Linq;
using System.Collections.Generic;

Dictionary<int, string> myDict = new Dictionary<int, string>();
// populate the dictionary with some key-value pairs ...

int largestKey = myDict.Keys.OrderByDescending(k => k).First();
240 chars
8 lines

Here, OrderByDescending sorts the keys from largest to smallest, and First returns the first (i.e. largest) one in the sequence. If the dictionary is empty, attempting to access First will throw an exception, so you may want to add a check for that before calling this code.

related categories

gistlibby LogSnag