简体   繁体   中英

How can I check in C# in the easiest way whether a variable is equal to one of the elements of a list? I want to do that without a long OR expression

I have a variable named as "Input". This variable is the value of an input field. On the other side I have a List containing lot of strings

List<string> names = new List<string>() { "Franz","Hans","Frank","Holger","Reiner".... };

I want to check whether the Operator's Input value is equal to one of the elements of my list. Normaly I would write a very long logical or expression like

If(Input=="Franz" || Input=="Hans" || Input=="Frank" ... ) // hundreds of or's..
{
  DoSomething();
}

Isn't there an easier way to check whether the "Input" variable's value is equal to one of the List's elements, without using logical OR expression?

You can use

if (names.Contains(Input))
{
  DoSomething();
}

This compares the items for a case-sensitve match. If you want to neglect differences in letter-casing, use

if (names.Any(x => Input.Equals(x, StringComparison.CurrentCultureIgnoreCase)))
{
  DoSomething();
}

You could optimize upper sample by storing the names as lowercase in the list directly.

You can use LINQ like so

List<string> names = new List<string>() { "Franz","Hans","Frank","Holger","Reiner"};        
if(names.Any(name => String.Equals(name, input)))
    Console.WriteLine("input is in list");
else
    Console.WriteLine("input is not in list");

dotnetfiddle for your convenience

If you want to do this just once, you can use names.Contains(Input) or names.Any(name=>name.Equals(Input,StringComparison.OrdinalIgnoreCase) . This is an expensive operation though, because it has to check all values every time looking for a match.

If you have to do this multiple times, it's better to load the strings into a HashSet or `Dictionary<string,...>. You can specify case-invariant matching by passing a case-invariant comparer to the collection's constructor:

_nameSet=new HashSet<string>(names,StringComparer.OrdinalIgnoreCase);

....
if (_nameSet.Contains(Input))
{
...
}

Here is a great way to do that by:

bool b = listOfStrings.Any(s=>myString.Contains(s));

using LINQ, which can be easily added.

So, then:

if(names.Any(s => s.Contains(Input))
{
  DoSomething();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM