Often if you have a unique list of items that you want to associate with some other item, a Dictionary
is a good solution. Each item in a dictionary is called a KeyValuePair
, and consists of two parts: a unique key
, which in this case would be the name, and a value
associated with that key, which in this case is an int.
For your example, it would look something like:
// The part in parenthesis specifies that the keys will be
// case-insensitive when doing comparisons, so you can search
// for "john", "John", or "JOHN", and get the same value back
private static Dictionary<string, int> nameValues =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
{"John", 1},
{"Jimmy", 2},
{"Mark", 3}
};
And a method for retrieving the int value for a name might look like:
private static int GetIntForName(string name)
{
var valueIfNotFound = -1;
return nameValues.ContainsKey(name) ? nameValues[name] : valueIfNotFound;
}
solved to many IF how to make quicker search c# [closed]