[英]Check if string contains in array
When I use a hard coded "4" in the second if, it works. 当我在第二个if中使用硬编码的“4”时,它可以工作。 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. 但我有一个动态字符串[] ProfileArray,并且想要检查,如果View08ListBox1Item的值包含/不包含ProfileArray中的一个字符串。 Why it does not work, when I change the "4" against the string[] ProfileArray? 当我对字符串[] ProfileArray更改“4”时,为什么它不起作用?
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 你可以使用Linq
ProfileArray.Any(x => x == View08ListBoxItem.Value.ToString()) //Contains
!ProfileArray.Any(x => x == View08ListBoxItem.Value.ToString()) //doesn't contain
non linq extension 非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());
Because ProfileArray is an array not a string. 因为ProfileArray是一个数组而不是一个字符串。
ProfileArray.Any(x => x == View08ListBox1Item.Value.ToString())
I think this can work. 我认为这可行。
In .NET 2.0 you can use 在.NET 2.0中,您可以使用
Array.IndexOf(ProfileArray, View08ListBox1Item.Value.ToString()) == -1
see http://msdn.microsoft.com/en-us/library/eha9t187%28v=vs.80%29.aspx 请参阅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())
您也可以使用非linq方式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. 无需如图所示迭代列表框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.