简体   繁体   中英

Check if string contains in array

When I use a hard coded "4" in the second if, it works. But I have a dynamic string[] ProfileArray and want to check, if the value of View08ListBox1Item contains/not contains with one of the strings in ProfileArray. Why it does not work, when I change the "4" against the string[] ProfileArray?

global:

static string[] ProfileArray;


case "Profile":
            foreach (ListItem View08ListBox1Item in View08ListBox1.Items)
            {
                if (View08ListBox1Item.Selected)
                {
                    if (!View08ListBox1Item.Value.ToString().Contains("4"))
                    {
                        //:do something
                    }
                    else
                    {
                        //:do something
                    }
                }
            }
            break;

this was my first idea, but it does not work:

case "Profile":
            foreach (ListItem View08ListBox1Item in View08ListBox1.Items)
            {
                if (View08ListBox1Item.Selected)
                {
                    if (!View08ListBox1Item.Value.ToString().Contains(ProfileArray))
                    {
                        //:do something
                    }
                    else
                    {
                        //:do something
                    }
                }
            }
            break;

you can use Linq

ProfileArray.Any(x => x == View08ListBoxItem.Value.ToString())  //Contains
!ProfileArray.Any(x => x == View08ListBoxItem.Value.ToString()) //doesn't contain

non linq extension

public static bool Contains<T>(this T[] array, T value) where T : class
{
   foreach(var s in array)
   {
      if(s == value)
      {
         return true;
      }

   }
  return false;
}
ProfileArray.Contains(View08ListBoxItem.Value.ToString());

Because ProfileArray is an array not a string.

ProfileArray.Any(x => x == View08ListBox1Item.Value.ToString())

I think this can work.

In .NET 2.0 you can use

Array.IndexOf(ProfileArray, View08ListBox1Item.Value.ToString()) == -1

see http://msdn.microsoft.com/en-us/library/eha9t187%28v=vs.80%29.aspx

A string cannot contain an array.. its the other way around.

You could use non-linq way too ProfileArray.Contains(View08ListBox1Item.Value.ToString())

Something like this maybe?

    bool found = false;
    for ( int i=0; i < ProfileArray.Length; i++)
    {
        if (View08ListBox1.SelectedItem.Value.ToString().Contains(ProfileArray[i])
        {
            found = true;
            break;
        }
    }

No need to iterate the listbox either as shown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM