0

I tried to check the given value is contained or not in particular field. Here the code what i wrote

bool _Contains = LabelDetails.Name.Contains("1");

Now want to check multiple value in cantains method.I tried like below but showing exception("No overload for method 'Contains' takes 3 arguments");

bool _Contains = LabelDetails.Name.Contains("1","2","3");
4

4 回答 4

5

That is because Contains just checks whether a substring exists in the given string. How should it know what you would mean by .Contains("foo", "bar")? Contains one of the two? Contains both? Contains them one after the other but not the other way around?

You could use a regex to check for existence of one of a given list of strings:

Regex.IsMatch("foo|bar|baz", LabelDetails.Name)

or create a few extension methods:

public static bool ContainsAll(this string s, params string[] args) {
    foreach (string x in args) {
        if (!s.Contains(x)) return false;
    }
    return true;
}

public static bool ContainsAny(this string s, params string[] args) {
    foreach (string x in args) {
        if (s.Contains(x)) return true;
    }
    return false;
}
于 2012-07-08T09:47:58.630 回答
2

I assumed that you have one textbox with text values.Then you want check some list values are contained or not in your text box and get the result in bool(true or false). True means you want to do something.False means you want to do something

List<string> Items = new List<string>() { "1", "2", "3" };
foreach (string item in Items)
{
    bool _Contains = TextBox.Text.Contains(item);
     if (_Contains == true)
        {
           //do something
        }
    else
       {
          //do something
       }
 }
于 2012-07-08T10:03:39.237 回答
0

You can achieve this by passing the name in a custom method also if you want you make this as extension method of the string class

public bool Contains(string name, params string[] pStrings )
{
    return pStrings.Any(pString => name.Contains(pString));
}
于 2012-07-08T10:09:01.357 回答
0

You can refer to In Extension method

https://stackoverflow.com/a/833477/649524

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}
于 2012-07-08T10:15:08.890 回答