mnlfischer
mnlfischer

Reputation: 397

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;

Upvotes: 2

Views: 2566

Answers (4)

Sayse
Sayse

Reputation: 43300

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());

Upvotes: 6

stevepkr84
stevepkr84

Reputation: 1657

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.

Upvotes: 1

Alessandro D&#39;Andria
Alessandro D&#39;Andria

Reputation: 8868

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

Upvotes: 2

Venkata Krishna
Venkata Krishna

Reputation: 15112

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

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

Upvotes: 1

Related Questions