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 ?
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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))
{
...
}
CodePudding user response:
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();
}