Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将字符串与列表框中的所有项目进行比较?_C#_Winforms - Fatal编程技术网

C# 如何将字符串与列表框中的所有项目进行比较?

C# 如何将字符串与列表框中的所有项目进行比较?,c#,winforms,C#,Winforms,我正在创建一个应用程序,允许用户存储有关其类的信息。我的应用程序中有一个按钮,允许用户输入信息,如果它与列表框中的任何项目匹配,那么它应该显示有关它的信息 只有在我按列表框的位置(例如项[0])指定特定项,然后将其转换为字符串时,我才能使其工作。我的目标是比较列表框中的所有项目 private void button3_Click(object sender, EventArgs e) { if (listBox2.Items[0].ToString() == "PersonalInfo

我正在创建一个应用程序,允许用户存储有关其类的信息。我的应用程序中有一个按钮,允许用户输入信息,如果它与
列表框
中的任何项目匹配,那么它应该显示有关它的信息

只有在我按
列表框
的位置(例如
项[0]
)指定特定项,然后将其转换为字符串时,我才能使其工作。我的目标是比较
列表框中的所有项目

private void button3_Click(object sender, EventArgs e)
{
    if (listBox2.Items[0].ToString() == "PersonalInfo")
    {
        label.Text = "test";               
    }
}

你可以用LINQ。。。大概是这样的:

if (listBox2.Items
            .Cast<object>()
            .Select(x => x.ToString())
            .Contains("PersonalInfo"))
{
    label.Text = "test";
}
foreach(var item in listBox2.Items)
{
  if(item.ToString() == stringToMatch)
  {
    label.Text = "Found a match";
  }
}
if(listBox2.Items
.Cast()
.Select(x=>x.ToString())
.包含(“个人信息”))
{
label.Text=“测试”;
}
或者,如果要获取第一次匹配的详细信息:

var match = listBox2.Items
                    .Cast<object>()
                    .FirstOrDefault(x => x.ToString() == "PersonalInfo");
if (match != null)
{
    // Use match here
}
var match=listBox2.Items
.Cast()
.FirstOrDefault(x=>x.ToString()==“PersonalInfo”);
如果(匹配!=null)
{
//在这里使用匹配
}

写一个循环来检查每个项目

foreach(var item in listBox2.Items)
{
  if (item.ToString()== "PersonalInfo")
  {
     label.Text = "test";
     break; // we don't want to run the loop any more.  let's go out              
  }    
}

您需要循环浏览列表中的所有项目。试着这样做:

if (listBox2.Items
            .Cast<object>()
            .Select(x => x.ToString())
            .Contains("PersonalInfo"))
{
    label.Text = "test";
}
foreach(var item in listBox2.Items)
{
  if(item.ToString() == stringToMatch)
  {
    label.Text = "Found a match";
  }
}
另一种更简单的实现(如果/当它找到匹配项时将停止,而不是继续检查每个项)是


我不认为lambda表达式是必要的。简单地做ListBox.Items.Contains(StringValue)应该可以。@Matt-我也这么想,但我相信问题是Items是一个
对象
s的集合,需要
到字符串
进行比较(我猜)。@Matt:你需要
Cast
调用才能使用LINQ的其余部分,你假设它已经是一个字符串。我的答案比Jon Skeet的答案更容易被接受?应该有一个徽章@Jim,可读性很有帮助,有些人不喜欢/不理解lambdas。请注意,第一个版本在WinForms和WebForms之间是可互换的,但我无法让最底层的版本与WebForms一起使用。我想它可能只需要
使用System.Linq
但这还不够。OP在问题中明确提到,作为问题解释的一部分,他们正在硬编码位置[0]的检查。如果它不重复这些信息,答案会更好。