Click here to Skip to main content
15,883,883 members
Articles / General Programming / String
Alternative
Tip/Trick

Dictionary<string,T>.BestMatch

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Feb 2013CPOL 14.6K   5   5
This is an alternative for "Dictionary.BestMatch"

Introduction

This Extension Method allows a partial match of a key of type string to select an item from a Dictionary. Multiple matches or no matches throw an ArgumentException.

The Code

The use of Linq removes the need for a foreach statement and the Take method avoids declaring a local variable for counting purposes. Finally, a switch statement is used instead of nested if blocks.

C#
public static T BestMatch<T>(this Dictionary<string, T> Source, string String)
{
    T result = default(T);

    if (Source.ContainsKey(String))
    {
        result = Source[String];
    }
    else
    {
        List<string> matches = Source.Keys.Where((s => s.StartsWith(String))).Take(2).ToList();
        switch (matches.Count)
        {
            case 0:
                throw (new ArgumentException("Unrecognized name", String));
            case 1:
                result = Source[matches[0]];
                break;
            default:
                throw (new ArgumentException("Ambiguous name", String));
        }
    }
    return result;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionBestMatch should return the Best Match even if there are more than 1 Pin
tidhar4-Feb-13 21:04
tidhar4-Feb-13 21:04 
GeneralRe: BestMatch should return the Best Match even if there are more than 1 Pin
PIEBALDconsult6-Feb-13 18:03
mvePIEBALDconsult6-Feb-13 18:03 
GeneralThoughts Pin
PIEBALDconsult3-Feb-13 7:53
mvePIEBALDconsult3-Feb-13 7:53 
GeneralRe: Thoughts Pin
George Swan6-Feb-13 21:50
mveGeorge Swan6-Feb-13 21:50 
GeneralRe: Thoughts Pin
PIEBALDconsult7-Feb-13 13:13
mvePIEBALDconsult7-Feb-13 13:13 
George Swan wrote:
local bool variable named found to act as a sort of
binary counter


Which is better than a List.


George Swan wrote:
as an exercise


Excellent. Thumbs Up | :thumbsup:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.