Reputation: 307
In my project I'm having a StringBuilder
which takes the selected value of dropdown lists.
StringBuilder builder = new StringBuilder();
builder.Append(ddl_model.SelectedValue);
builder.Append(ddl_language.SelectedValue);
foreach (string str in list)
{
if (str.Contains(builder.ToString()))
{
lstpdfList.Items.Add(str);
}
}
It works with one value. I would like to make that I can check if contains two or more words.
I have a file like PM12_Manual_Rev1_EN . Now I can find if it contains PM12. But there is a lot of them. So I would like to check if contains PM12 + EN.
Upvotes: 0
Views: 3509
Reputation: 2545
You should use String.Contains Method, its the easiest way! It returns a value indicating whether the specified String object occurs within this string.
@Shaks has right.
Upvotes: 0
Reputation: 25844
You could use regexes.
string testString ="PM12_Manual_Rev1_EN";
var wordRegex = new Regex( "PM12.*EN", RegexOptions.IgnoreCase );
if (wordRegex.IsMatch( testString ))
{
Console.WriteLine("we've found multiple matches, REGEX edition");
}
Or you could use Contains with Linq like this:
string testString ="PM12_Manual_Rev1_EN";
var checkWords = new List<String>() {"PM12", "EN"};
if(checkWords.All(w => testString.Contains(w)))
{
Console.WriteLine("we've found multiple matches");
}
Upvotes: 0
Reputation: 16618
1) Don't call builder.ToString() inside the foreach, it will rebuild the string everytime, and it defeats the performance purpose of StringBuilder.
2) Don't use a StringBuilder, use a List in which you store the words you want to match for, if each selected value may contain several words, split them:
var keywords = new List<string>();
keywords.AddRange(ddl_model.SelectedValue.Split(' '));
keywords.AddRange(ddl_language.SelectedValue.Split(' '));
foreach(string str in list)
if (keywords.Any(keyword => str.Contains(keyword))
lstpdfList.Items.Add(str);
Upvotes: 4