C#使用Select或Where not working进行谓词化

Tra*_*v92 2 c# for-loop predicate where-clause

在C#中使用谓词遇到一些问题.我有两组代码(我认为两者都应该完成相同的结果),但一个代码永远不会有效.我问的原因是我需要这个谓词出现几次不同的元素,所以我想尽可能保持最小(非工作的非常简单,而另一个包含很多行).

1不工作:

ItemViewModel item = (App.ViewModel.All_Items.Where(x => (x as ItemViewModel).Name == my_list_of_strings.ElementAt(2)) as ItemViewModel);
Run Code Online (Sandbox Code Playgroud)

同时使用"选择"而不是"何处"不起作用.

2工作:

foreach (ItemViewModel it in App.ViewModel.All_Items)
{
  if (item.Name == my_list_of_strings.ElementAt(2))
  {
    MessageBox.Show("Success!!");
    item = it;
    continue; // Leave loop
  }
}
Run Code Online (Sandbox Code Playgroud)

我可能忽略了一些愚蠢的东西,但如果有人知道解决方案,那就太棒了!

谢谢.

Gar*_*y.S 5

IEnumerable<T>.Where(Func<T, bool>)返回一个集合,但它看起来像你想要的是一个单独的元素.有几种选择:

IEnumerable<T>.FirstOrDefault(Func<T, bool>) // returns null if no element found
IEnumerable<T>.First(Func<T, bool>) // throws if no element is found

// These throw an error if more than one element exists that matches the query
IEnumerable<T>.SingleOrDefault(Func<T, bool>) // returns null if no element found
IEnumerable<T>.Single(Func<T, bool>) // throws if no element is found
Run Code Online (Sandbox Code Playgroud)

在您的示例中,它将是:

// Just replace "Where" with "FirstOrDefault"
ItemViewModel item = (App.ViewModel.All_Items.FirstOrDefault(x => (x as ItemViewModel).Name == my_list_of_strings.ElementAt(2)) as ItemViewModel);
Run Code Online (Sandbox Code Playgroud)