-2

I have a dictionary DateTime, DataTable

Key Values

2019/07/01 Column A | B

                  1 | 1

2019/07/02 Column A | B

                  3 | 4

2019/07/03 Column A | B

                  5 | 4

I would like to use linq to find the key of the dictionary with maximum value of column A in the dict.

In above case, my expected result is "2019/07/03"

I am new in linq. Is it possible for above use? How to do?

J.Y.527
  • 13
  • 3

3 Answers3

1

While .OrderByDescending(x=> x.Key).FirstOrDefault()?.Key; will give you the correct answer, it will result in first sorting the values which is time and memory inefficient.

What you want to do is scan all your values once without memory consumption:

 KeyValuePair<MyKey, MyValue> maxKey;
 if (list.Count > 0)
 {
    maxKey = list.Aggregate(list.First(), (first,second)=>first.Value.A>second.Value.A?first:second);
 }
Bruno Belmondo
  • 2,114
  • 6
  • 18
0

Another one example.

Dictionary<DateTime, int> example = new Dictionary<DateTime, int>() 
            { 
                {new DateTime(2019,07,01), 1 },
                {new DateTime(2019,07,02), 2 },
                {new DateTime(2019,07,03), 3 }
            };
var HighestKey = example.Keys.Max(); 
Brijesh
  • 91
  • 1
  • 14
-1

Please try below solution, I am sure it will work.

<DictionaryName>.OrderByDescending(x => x.Key).First();
deHaar
  • 11,298
  • 10
  • 32
  • 38
Ninad
  • 1
  • 2