Click here to Skip to main content
15,891,033 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 

Thanks for your comments. What I actually wrote was, "The Take method avoids declaring a local variable for counting purposes." Your method uses a foreach statement and that has the same advantage but you also need to declare the local bool variable named found to act as a sort of binary counter. I take your point about hidden if statements inside Linq but it does, in my opinion, produce neat code. I'm learning Linq and wrote the method as an exercise. It wasn't, in any way, a criticism of your excellent article. Best wishes, George.


GeneralRe: Thoughts Pin
PIEBALDconsult7-Feb-13 13:13
mvePIEBALDconsult7-Feb-13 13:13 

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.