Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

Dictionary<string,T>.BestMatch

0.00/5 (No votes)
3 Feb 2013CPOL 15.1K  
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)