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;
}