Reputation:
If my statement contains two conditions:
string searchx = "some string";
if ((searchx.Contains("a1")) || (searchx.Contains("a2")))
{
...
}
But how to get list of values with single variable for statement?
If I got a1, a2, a3, a4, a5, a6, a7, a8, a9...
Can I do it somehow this way, seems it is wrong attempt:
var valueList = new List<string> { "a1", "a2", "a3", "a4"};
But just to explain what I want to do, so if any value exist under valueList
, condition is accepted:
if (searchx.Contains(valueList))
{
...
}
The best if I can get multiple value return I guess or any other way to get statement with updated list of values through single variable of any other way, which can work for me this way?
Upvotes: 2
Views: 495
Reputation: 787
This has worked for me:
if (valueList.Any(x => searchx.Contains(x)))
{
}
or even shorter (thanks to rajeeshmenoth)
if(valueList.Any(searchx.Contains))
Upvotes: 8
Reputation: 1750
You can use the Linq :
bool b = valueList.Any(searchx.Contains);
Try this :
string searchx = "a8";
var valueList = new List<string>{"a1", "a2", "a3", "a4"};
if (valueList.Any(searchx.Contains))
Console.WriteLine("Data Matching..!!");
else
Console.WriteLine("Not Matching..!!");
Demo :Click here
Upvotes: 0
Reputation: 861
Not the best solution, but works.
bool containsValue(string search)
{
var valueList = new List<string> { "a1", "a2", "a3", "a4"};
foreach (string s in valueList)
{
if(search.Contains(s))
return true;
}
return false;
}
and use it like :
if (containsValue(searchx))
{
... do something ...
}
Upvotes: 1
Reputation: 730
You can make a foreach loop
string search = "GIVE A STRING";
List<string> DataList = new List<string> {"a1", "a2", "a3",.....};
foreach(string Data in DataList)
{
if(search.Contains(Data))
{ //TODO }
}
Upvotes: -1
Reputation: 13628
You can try and use Except
if (valueList.Except(searchx).Any())
{
}
Upvotes: 3