[英]Check if string contains in array
當我在第二個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;
你可以使用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());
因為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
字符串不能包含數組..反過來說。
您也可以使用非linq方式ProfileArray.Contains(View08ListBox1Item.Value.ToString())
這樣的事可能嗎?
bool found = false;
for ( int i=0; i < ProfileArray.Length; i++)
{
if (View08ListBox1.SelectedItem.Value.ToString().Contains(ProfileArray[i])
{
found = true;
break;
}
}
無需如圖所示迭代列表框。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.