Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.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#_Wpf_Listbox - Fatal编程技术网

C# 如何通过给定字符串在列表框中选择字符串条目而不循环?

C# 如何通过给定字符串在列表框中选择字符串条目而不循环?,c#,wpf,listbox,C#,Wpf,Listbox,WPF中没有listbox.findString。假设我们有一个listbox: var entries = listBox.Items.Where(item => item.ToString() == "something"); ListBox b = new ListBox(); 然后您可以使用LINQ: int index = b.Items.IndexOf(( from ListBoxItem a in b.Items

WPF中没有listbox.findString。

假设我们有一个listbox:

var entries = listBox.Items.Where(item => item.ToString() == "something");
ListBox b = new ListBox();
然后您可以使用LINQ:

        int index = b.Items.IndexOf((
            from ListBoxItem a in b.Items
            where a.Content.ToString() == "something"
            select a).First());
或者您可以使用foreach:

        foreach (ListBoxItem lbi in b.Items)
        {
            if (lbi.Content is string && (string)lbi.Content == "something")
            {
                index = b.Items.IndexOf(lbi);
                break;
            }
        }

在大多数情况下,您希望将ListBox的ItemsSource绑定到代码中实现IEnumerable的实际集合,然后使用.Where.First语句查找字符串的第一次出现,如下所示:

List<string> lstb = new List<string>() { "StringA", "StringB", "StringC" };
string stringC = lstb.Where(s => s == "StringC").First();

但是,我强烈建议您花点时间学习数据绑定和MVVM模型,它大大简化了与WPF控件的交互。

这是一个问题还是一个语句?标题是一个问题,内容是一个语句使用LINQ将字符串设置为某个值?您的代码相当于字符串s=something。无论哪种方式都将有一个循环,findString有一个循环LINQ有一个循环,因此foreach方法将执行相同的操作比较a.Content==something将使用Object.ReferenceEquals,因此语句很可能会因InvalidOperationException而失败。您需要将.Content强制转换为字符串或调用ToString。
yourListBox.SelectedItem = stringC;