C# Code Optimization -- Finding nearest key in a SortedList Just wondering if anyone can see a way to optimize this piece of code.  It is a key piece of my program and needs to run as quickly as possible. The part of the code I am unsure of is the while loop for finding the nearest key -- but any assistance with optimizing the code would be appreciated.

// TODO: Move to snippets lib or create a new collection type that supports this feature
private string _getTrait(SortedList&lt;decimal, string&gt; thisList, decimal thisValue)
{
    // Check to see if we need to search the list.
    if (thisList == null || thisList.Count &lt;= 0) { return null; }
    if (thisList.Count == 1) { return thisList.Values[0]; }

    // Setup the variables needed to find the closest index
    int lower = 0;
    int upper = thisList.Count - 1;
    int index = (lower + upper) / 2;

    // Find the closest index (rounded down)
    bool searching = true;
    while (searching)
    {
        int comparisonResult = Decimal.Compare(thisValue, thisList.Keys[index]);
        if (comparisonResult == 0) { return thisList.Values[index]; }
        else if (comparisonResult &lt; 0) { upper = index - 1; }
        else { lower = index + 1; }

        index = (lower + upper) / 2;
        if (lower &gt; upper) { searching = false; }
    }

    // Check to see if we are under or over the max values.
    if (index &gt;= thisList.Count - 1) { return thisList.Values[thisList.Count - 1]; }
    if (index &lt; 0) { return thisList.Values[0]; }

    // Check to see if we should have rounded up instead
    if (thisList.Keys[index + 1] - thisValue &lt; thisValue - (thisList.Keys[index])) { index++; }

    // Return the correct/closest string
    return thisList.Values[index];
}


I am using C#, .net4.0 -- I need to use a Generic SortedList ( http://msdn.microsoft.com/en-US/library/ms132319(v=vs.100).aspx )
Your loop is pretty well written. The only thing that sticks out to me is your use of a constant in the while loop and manually breaking.  I also prefer to use a slightly different version of CompareTo, but it doesn't make much difference:

while ( (lower&lt;=upper))
{
    int comparisonResult = thisValue.CompareTo( thisList.Keys [index]);
    if (comparisonResult == 0) { return thisList.Values[index]; }

    if (comparisonResult &lt; 0)
    {
        upper = index - 1;
    }
    else
    {
        lower = index + 1;
    } 
    index = (lower + upper) / 2; 
}


You might also be looking for a solution that's just easier to read or shorter. Are you familiar with LINQ? This is one possibility for how your function might look.

    private static string GetTraitRefactor (SortedList&lt;decimal, string&gt; thisList, decimal thisValue)
    {
        var keys = thisList.Keys;
        var nearest = thisValue -
            keys.Where(k =&gt; k &lt;= thisValue)
            .Min(k =&gt; thisValue - k);
        return thisList[nearest];
    }