检查字符串是否包含在数组中

时间:2013-08-14 15:26:10

标签: c# asp.net arrays string contains

当我在第二个if中使用硬编码“4”时,它可以工作。但我有一个动态字符串[] ProfileArray,并且想要检查,如果View08ListBox1Item的值包含/不包含ProfileArray中的一个字符串。当我对字符串[] ProfileArray更改“4”时为什么它不起作用?

全局:

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;

这是我的第一个想法,但它不起作用:

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

4 个答案:

答案 0 :(得分:6)

你可以使用Linq

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

非linq扩展

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

答案 1 :(得分:2)

因为ProfileArray是一个不是字符串的数组。

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

我认为这可行。

在.NET 2.0中,您可以使用

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

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

答案 2 :(得分:1)

字符串不能包含数组..反之亦然。

您也可以使用非linq方式ProfileArray.Contains(View08ListBox1Item.Value.ToString())

答案 3 :(得分:1)

这样的事可能吗?

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

无需如图所示迭代列表框。

相关问题