[英]How to search listbox items with only part of its text
I have a C# WinForms application. 我有一个C#WinForms应用程序。 There is a listbox filled with values in this format: 有一个列表框,其中填充了以下格式的值:
category:user:id
Food:tester:17
etc. 等等
Now, I need to get if an item is included in this Listbox, knowing only the category and ID, I don't know the user. 现在,我需要获取一个项目是否包含在此列表框中,并且只知道类别和ID,不知道用户。 So technically, I need to do something like this (pseudocode): 因此,从技术上讲,我需要执行以下操作(伪代码):
if(MyListBox.Items.Contains("Food:*:17"))
where the * would mean "anything". *表示“任何”。 Is there a way of doing this? 有办法吗?
Assuming the listbox is filled directly with strings, the easiest way would be a combination of linq and regex: 假设列表框直接用字符串填充,最简单的方法是linq和regex的组合:
if(MyListBox.Items.Cast<string>().Any(s => Regex.IsMatch(s, "Food:.*:17"))) //(For RegEx: using System.Text.RegularExpressions )
or more strict, if the items are always a combination of value:value:value and you only check the first and third value: 或更严格,如果项目始终是value:value:value的组合,而您仅检查第一个和第三个值:
if (MyListBox.Items.Cast<string>().Any(s => { var values = s.Split(':'); return values[0] == "Food" && values[2] == "17"; }))
try something like this 尝试这样的事情
var res =
MyListBox.items.SingleOrDefault(
item =>
item.Contains("Food:") && item.Contains(":17") &&
item.IndexOf(":17", StringComparison.InvariantCulture) >
item.IndexOf("Food:", StringComparison.InvariantCulture));
if ( !string.IsNullOrEmpty(res))
{
//your code here
}
}
You could do something like 你可以做类似的事情
var value = MyListBox.Items.Cast<string>()
.FirstOrDefault(m => m.Contains("Food:") && m.Contains(":17"));
if (value != null) {
// you have a match
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.