56

I have

Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>();

How I can get an Guid which has MAX value?

Mathieu
  • 4,449
  • 7
  • 41
  • 60
Terminador
  • 1,328
  • 4
  • 14
  • 23
  • 3
    possible duplicate of [Get Max() of alphanumeric value](http://stackoverflow.com/questions/7268605/get-max-of-alphanumeric-value) – M.Babcock Apr 24 '12 at 02:06
  • Please try to do your own research before asking question on SO. – M.Babcock Apr 24 '12 at 02:07
  • 1
    Since "GUID" stands for "globally unique identifier," it seems incredibly odd that you would want a "maximum" value at all. A GUID is used because of its uniqueness; I cannot think of a real world application where it makes sense to think of them as ordered at all. – jpmc26 May 08 '14 at 10:15
  • I think perhaps you miss the point entirely jpmc26. Suppose for instance I have var fooDict = new Dictionary(); where the string value is a GUID and I want to know which which kvp has the highest int value (using MoreLinq): var biggestIntKey = fooDict .MaxBy(kvp => kvp.Value).Key; var biggestInt = fooDict [biggestIntKey]. And I think just about anyone reading SO knows what a GUID is. Not helpful. – GDB Nov 20 '15 at 15:59
  • Exactly same question [here](https://stackoverflow.com/q/2805703/465053). – RBT Sep 04 '17 at 07:46

8 Answers8

127

Since this was the accepted answer, I'll try to cover every possible meaning of the question:

var dict = 
    new Dictionary<string, int> 
    { 
        ["b"] = 3, 
        ["a"] = 4 
    };

// greatest key
var maxKey = dict.Keys.Max(); // "b"

// greatest value
var maxValue = dict.Values.Max(); // 4

// key of the greatest value
// 4 is the greatest value, and its key is "a", so "a" is the answer.
var keyOfMaxValue = 
    dict.Aggregate((x, y) => x.Value > y.Value ? x : y).Key; // "a"

Note: the question has System.Guid as the key type. It might not make sense to ask "what is the greatest GUID", since they are simply intended to be unique values, rather than represent any orderable concept. Nonetheless, the above code will work with any type that supports the > operator, string and int being chosen here for conciseness.

Asik
  • 21,506
  • 6
  • 72
  • 131
53

This works great. It will return the GUID for the MAX date.

Dictionary<Guid, DateTime> d = new Dictionary<Guid, DateTime>(); 
var guidForMaxDate = d.FirstOrDefault(x => x.Value == d.Values.Max()).Key;
Papa Burgundy
  • 6,397
  • 6
  • 42
  • 48
  • 5
    Nice, though I'd get that `d.Values.Max()` out into a variable in advance, otherwise it'll probably repeat that search for Max() in every single iteration. – Nyerguds Sep 21 '17 at 07:21
12
            var maxGuid = Guid.Empty;
            var maxDateTime = DateTime.MinValue;
            foreach (var kvp in d)
            {
                if (kvp.Value > maxDateTime)
                {
                    maxGuid = kvp.Key;
                    maxDateTime = kvp.Value;
                }
            }
            Console.WriteLine("Guid of max date is: " + maxGuid.ToString());
Steven P
  • 1,956
  • 1
  • 16
  • 17
  • 1
    Re-reading the question, I think this is the correct interpretation, and the only answer that gives the correct result (although I suspect it could be made shorter with LINQ, it won't be any faster than this explicit loop). – Ben Voigt Apr 24 '12 at 02:14
  • 1
    @BenVoigt explicit loop is best deal here in terms of clarity. Another post [here](https://stackoverflow.com/q/2805703/465053) with some very good answers. The accepted answer in this post claims to have single scan using LINQ. – RBT Sep 04 '17 at 07:52
6

Ordering your data in the first place could be one solution.

var maxGuid = d.OrderByDescending(x => x.Value).FirstOrDefault().Key;
felixperreault
  • 199
  • 2
  • 2
  • Sorting the entire list is a bit expensive in comparison to just returning the highest value – Bill Tarbell Jun 24 '19 at 19:52
  • 1
    OrderByDescending returns an IOrderedEnumerable (which is an IEnumerable exposing more ordering options, like ThenBy or ThenByDescending). This code will only go through the data once, to get the highest value, then it will output the first one. It will not reorder ALL the list unless you materialize it and store it somewhere, like in a variable, with .ToArray(), for example. FirstOrDefault does nothing more than take the first item if it exists, and does not iterate over the values. How is it different than other answers? Do you have any idea how linq .Max or .MaxBy extensions work? – felixperreault Dec 11 '19 at 19:12
5

Guid implements IComparable, so:

d.Keys.Max()

Also it is not clear why one would want to do so...

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
3

The accepted answer didn't work for me. The following code (using MoreLinq) did the job though:

var fooDict = new Dictionary<string, int>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var biggestInt = fooDict[keyForBiggest];
GDB
  • 3,379
  • 2
  • 26
  • 38
3

By using LINQ on dictionary.

var MaximumValue = dict.FirstOrDefault(x => x.Value.Equals(dict.Values.Max()));
Hamza Khanzada
  • 1,439
  • 1
  • 22
  • 39
0

Another way might helps to get Single KeyValuePair.

KeyValuePair<char, int> GuidKeyPair = guidDict.FirstOrDefault( MaxGuid => MaxGuid.Value == guidDict.Values.Max());
Sai
  • 1,376
  • 2
  • 15
  • 25