Good way to get the key of the highest value of a Dictionary in C#

前端 未结 10 967
花落未央
花落未央 2020-12-04 17:33

I\'m trying to get the key of the maximum value in the Dictionary results.

This is what I have so far:

double max          


        
10条回答
  •  甜味超标
    2020-12-04 17:48

    My version based off the current Enumerable.Max implementation with an optional comparer:

        public static TSource MaxValue(this IEnumerable source, Func function, IComparer comparer = null)
        {
            comparer = comparer ?? Comparer.Default;
            if (source == null) throw new ArgumentNullException(nameof(source));
    
            TSource max = default;
            TConversionResult maxFx = default;
            if ( (object)maxFx == null) //nullable stuff
            {
                foreach (var x in source)
                {
                    var fx = function(x);
                    if (fx == null || (maxFx != null && comparer.Compare(fx, maxFx) <= 0)) continue;
                    maxFx = fx;
                    max = x;
                }
                return max;
            }
    
            //valuetypes
            var notFirst = false;
            foreach (var x in source) 
            {
                var fx = function(x);
                if (notFirst)
                {
                    if (comparer.Compare(fx, maxFx) <= 0) continue;
                    maxFx = fx;
                    max = x;
                }
                else
                {
                    maxFx = fx;
                    max = x;
                    notFirst = true;
                }
            }
            if (notFirst)
                return max;
            throw new InvalidOperationException("Sequence contains no elements");
        }
    

    Example usage:

        class Wrapper
        {
            public int Value { get; set; }    
        }
    
        [TestMethod]
        public void TestMaxValue()
        {
            var dictionary = new Dictionary();
            for (var i = 0; i < 19; i++)
            {
                dictionary[$"s:{i}"] = new Wrapper{Value = (i % 10) * 10 } ;
            }
    
            var m = dictionary.Keys.MaxValue(x => dictionary[x].Value);
            Assert.AreEqual(m, "s:9");
        }
    

提交回复
热议问题