How do I compare a string against a huge set of predefined strings in C#?
In a C# program I have a String
variable and I want to compare it against say one hundred predefined (hardc开发者_JAVA百科oded) string literals so that I know whether it matches any of those predefined strings.
I can of course write a switch
or a chain of if-else if
s but this way strings are interleaved with control statements and IMO that decreases readability and makes planting an error easier.
Is there a way to somehow list all strings so that they are located as close to each other in code as possible?
You can use HashSet (or Dictionary) and then just check if the key is present or not.
If there is no way but to hardcode the strings, you can define them in an HashSet:
var strs = new HashSet<string>{ "Str1","Str2","Str3" };
Ignoring case :
var strs = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Str1","Str2","Str3" };
And :
var found = strs.Contains(myVariable);
If I were you I would put all these strings in a List
and do this comparison in a foreach
or contains
.
Two ways I have approached this
- Use a List and invoke "contains" or
- Use a long string (as
string lits = "one|two|three"
) and then find then calllits.indexOf(otherString + "|")
, if the value is greater than -1 then you have a hit...
Cheers
CEC
private const string _searched = "one|two|three";
private void button1_Click(object sender, EventArgs e)
{
string search = "two" + "|";
if (_searched.IndexOf(search) > -1)
{
//do something
}
}
private List<string> _searchedList = new List<string>() { "one", "two", "three" };
private void button2_Click(object sender, EventArgs e)
{
string search = "two";
if (_searchedList.Contains(search))
{
//do something
}
}
If performance is paramount and if the strings to search are known at compile time you can create a minimal perfect hash and store the strings in an array.
var stringTable = new[] { "The", "quick", "brown", ... };
var input = "fox";
var hash = ComputeMinimalPerfectHash(input);
var match = stringTable[hash];
if (input == match)
// You have found a match.
Obviously generating the code for ComputeMinimalPerfectHash
based on the strings is the tricky part.
If this list does not change you place them all into a collection and loop through the collection and compare the strings.
Using a switch statement or if-else ifs wouldn't be correct in the case of one hundred cases.
Create a dictionary of (string, string), add all your predefined strings with the key and value as the same string. You can use dictionary.ContainsKey() function to check if the input string exists in the dictionary.
This will also be faster than looping through all the strings and doing comparison as dictionary will use a hash function to locate the keys faster instead of looping.
List<String> strings = new List<String>{"String 1", "String 2", "String 3" ...};
if (strings.Contains(stringValue))
{
}
精彩评论