Search code examples
c#keyvaluepair

Partition Keys in List<KeyValuePair> c#


I have a List of KeyValuePairs

var hitCoord = new List<KeyValuePair<int, double>>()

and sorted like this (descending by Key)

hitCoord.Sort((a, b) => (b.Key.CompareTo(a.Key)));

I can find the total highest Value with

hitCoord.Sort((a, b) => (b.Value.CompareTo(a.Value)));

(^ maybe that can be used for the following query?)

I would like to partition the Keys in my list such that I can find Values that meet a condition within the specified range of keys.

i.e. I would like to find the highest Value and Lowest Value in a range of (int)Keys

for (i=0; i<hitCoord.Count; i++)
{
     if (hitCoord[i].Key > (int lowerbound) && hitCoord[i].Key < (int upperBound)
     {
          find highest Value?
     }
}

Not sure if that is at all on the right track. I am new to programming and very new to KeyValuePairs. Any help you can offer on this matter is much appreciated! Thank you!


Solution

  • Finding the max value in a specified range of keys could be solved by using LINQ (using System.Linq;) like this:

    hitCoord.Where(c => c.Key > lowerbound && c.Key < upperbound).Max(c => c.Value);
    

    The approach:

    1. Use Where to filter all items with key in range
    2. Use Max to get the max value

    You could adapt and extend the query also with more checks and constraints. Some basic queries are described in Basic LINQ Query Operations (C#).