Reputation: 37
I'm trying to implement a simple search function. I have a string array which contains all words which was typed in from the user to search. And I have another string which contains data like User Name, content... So what I want to do is to check is Name contains any of the elements in the search or String array. Right now I have a loop which checks one word at a time and concatenates the result in an IEnumerable.
Does anyone know a faster way of doing this search? Like String.ContainsAny(Search[])
Upvotes: 3
Views: 7304
Reputation: 1775
Two solutions to this problem for example:
Solution 1
private void findDateColumn() {
string stringToCheck = "date";
int stringToCheckIndex = -1;
string elementInArray = "Not Defined or Not Found";
if (Array.Exists<string> (headers, (Predicate<string>) delegate (string s)
{
stringToCheckIndex = s.IndexOf (stringToCheck,StringComparison.OrdinalIgnoreCase);
elementInArray = s;
return stringToCheckIndex > -1;
}))
{
dateColTitle.Text = elementInArray; //a textbox to show the output
}
}
Solution 2
I'm using @Lev answer, which seems simpler and shorter plus giving the same result:
private void setDateColumnTitle ()
{
dateColTitle.Text = "Not Defined or Not Found";
var match = headers.FirstOrDefault(c => c.IndexOf("date", StringComparison.OrdinalIgnoreCase) > -1);
if (match!=null)
dateColTitle.Text = match;
}
Upvotes: 0
Reputation: 62504
using System.Linq;
string[] searchItems = ...
string input = "This is the input text";
// Check whether at least one match found
bool matchFound = input.Any(w => input.Contains(w));
// Count all matches
int matchesCount = input.Where(w => input.Contains(w))
.Count();
Upvotes: 2
Reputation: 17701
you can do like this...
return array.Any(s => s.Equals(myString))
or try like this....
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (x.Contains(stringToCheck))
{
// Process...
}
}
or Something like this
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) {
return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
Console.WriteLine("Found!");
}
Upvotes: 1