0

I have a Dictionary of type

Dictionary<int, GValue> 

where GValue is an object that contains two double values P1 and P2

How can I get max P1 and P2 from this Dictionary?

I have tried so far this

c.CalculateGraphMetrics(nodeXLControl1.Graph).Max(s => s.Value.P1);

It gives me no error, but result shows on debug

Expression cannot contain Lambda expressions
John Willemse
  • 6,608
  • 7
  • 31
  • 45
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
  • How can i get the key associated with value – Rajeev Kumar May 03 '13 at 07:48
  • possible duplicate of [How to use LINQ to select object with minimum or maximum property value](http://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value) – nawfal Jul 19 '14 at 18:49

2 Answers2

1

Immediate window does not support lambda expressions.

Your code is ok, but to be able to get this result in immediate window you have to have it as method in a class and compile it.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • Well, resolved this issue. How can i get the key associated with value – Rajeev Kumar May 03 '13 at 07:36
  • @RajeevKumar Max is not very convenient for that, but there is similar question that uses custom comparer to keep whole object instead of just one feel in result... http://stackoverflow.com/questions/1101841/linq-how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-ret and http://stackoverflow.com/questions/11520666/get-from-a-listt-the-record-with-the-maximum-value-of-a-specific-property/11520938#11520938 – Alexei Levenkov May 03 '13 at 07:38
1

Re. getting the key corresponding to the maximum value: I see a lot of complicated implementations of MaxBy when you can use one of the overloads of Aggregate to similar effect:

var keyForMaxP1 = dict.Keys.Aggregate((i, j) => dict[i].P1 >= dict[j].P1 ? i : j);
var keyForMaxP2 = dict.Keys.Aggregate((i, j) => dict[i].P2 >= dict[j].P2 ? i : j);

Edit: If you want to get multiple maximum keys, you'll need something like

var allMaxKeysForP1 = dict.Keys.Aggregate(
    new { Value = double.NegativeInfinity, Keys = new List<int>() },
    (a, k) =>
        {
            if (a.Value > dict[k].P1) return a;
            if (a.Value.Equals(dict[k].P1))
            {
                a.Keys.Add(k);
                return a;
            }
            return new { Value = dict[k].P1, Keys = new List<int> { k } };
        },
    a => a.Keys);

at which point you might want to consider implementing this as an AllMaxBy method.

Rawling
  • 49,248
  • 7
  • 89
  • 127