Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Dictionary<string,T>.BestMatch

, 3 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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)

Share

About the Author

George Swan
Student
Wales Wales
No Biography provided

Comments and Discussions

 
QuestionBestMatch should return the Best Match even if there are more than 1 Pinmembertidhar4-Feb-13 22:04 
GeneralRe: BestMatch should return the Best Match even if there are more than 1 PinmemberPIEBALDconsult6-Feb-13 19:03 
GeneralThoughts [modified] PinmemberPIEBALDconsult3-Feb-13 8:53 
GeneralRe: Thoughts PinmemberGeorge Swan6-Feb-13 22:50 
GeneralRe: Thoughts PinmemberPIEBALDconsult7-Feb-13 14:13 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411028.1 | Last Updated 3 Feb 2013
Article Copyright 2013 by George Swan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid