Click here to Skip to main content
13,904,766 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


5 bookmarked
Posted 3 Feb 2013
Licenced CPOL


, 3 Feb 2013
Rate this:
Please Sign up or sign in to vote.
This is an alternative for "Dictionary.BestMatch"


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];
        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]];
                throw (new ArgumentException("Ambiguous name", String));
    return result;


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


About the Author

George Swan
Wales Wales
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionBestMatch should return the Best Match even if there are more than 1 Pin
tidhar4-Feb-13 21:04
membertidhar4-Feb-13 21:04 
GeneralRe: BestMatch should return the Best Match even if there are more than 1 Pin
PIEBALDconsult6-Feb-13 18:03
protectorPIEBALDconsult6-Feb-13 18:03 
GeneralThoughts Pin
PIEBALDconsult3-Feb-13 7:53
protectorPIEBALDconsult3-Feb-13 7:53 
GeneralRe: Thoughts Pin
George Swan6-Feb-13 21:50
memberGeorge Swan6-Feb-13 21:50 
GeneralRe: Thoughts Pin
PIEBALDconsult7-Feb-13 13:13
protectorPIEBALDconsult7-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 3 Feb 2013
Article Copyright 2013 by George Swan
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid