带Select或Where的C#谓词不起作用

带Select或Where的C#谓词不起作用,c#,for-loop,where-clause,predicate,C#,For Loop,Where Clause,Predicate,C#中的谓词有问题。 我有两套代码(我相信这两套代码应该可以实现相同的结果),但其中一套根本不起作用。我问这个问题的原因是我需要这个谓词在不同的元素中出现几次,因此我希望尽可能地将其最小化(非工作谓词非常简单,而另一个包含许多行) 1不工作: 也可以使用“选择”而不是“哪里不起作用” 2工作: 我可能忽略了一些愚蠢的事情,但如果有人知道解决方案,那就太好了 谢谢。IEnumerable。其中(Func)返回一个集合,但它看起来像是一个元素。有两种选择: IEnumerable<T>.

C#中的谓词有问题。 我有两套代码(我相信这两套代码应该可以实现相同的结果),但其中一套根本不起作用。我问这个问题的原因是我需要这个谓词在不同的元素中出现几次,因此我希望尽可能地将其最小化(非工作谓词非常简单,而另一个包含许多行)

1不工作: 也可以使用“选择”而不是“哪里不起作用”

2工作: 我可能忽略了一些愚蠢的事情,但如果有人知道解决方案,那就太好了

谢谢。

IEnumerable。其中(Func)
返回一个集合,但它看起来像是一个元素。有两种选择:

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
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
  }
}
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
// 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);