Link to home
Start Free TrialLog in
Avatar of QPR
QPRFlag for New Zealand

asked on

If string value is one of

If I want to compare a string value against a list of possible matches, what is the best way?
An enum list? If so, how do I cycle through it looking for a match?
Or some other way?
The list to compare against would be constants
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As Andy Mentioned you can proceed with Contains, but will return More tahn one results to go with excat match

List<String> li = new List<String>();
            li.Add("Foo");
            li.Add("Bar");
            li.Add("etc");

var seelctedObject = (from obj in li 
                                      where string.Equals(obj,"Foo")
                                         select obj);

Open in new window

Please look at the last tip in the article. If you have string array you can convert into list and search using contains.

https://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4148-Some-ASP-NET-Practical-tips.html
Avatar of QPR

ASKER

How will the first response return more than one match?
I am using this

if (li.Contains(testWord, StringComparer.OrdinalIgnoreCase))

and it is working fine - is there a bug around the corner I haven't noticed?
>>How will the first response return more than one match?

It can't - Contains checks if the list has at least one item that matches.  (Why would you add duplicates to your list that you check against?)
Avatar of QPR

ASKER

That's what I thought - thanks