在 C# 中的谓词方面遇到一些问题。 我有两套代码(我相信这两套代码应该实现相同的结果),但其中一套永远不会工作。我问的原因是我需要这个谓词在不同的元素中出现几次,所以我想让它尽可能少(非工作的谓词非常简单,而另一个包含很多行)。
1 不工作:
ItemViewModel item = (App.ViewModel.All_Items.Where(x => (x as ItemViewModel).Name == my_list_of_strings.ElementAt(2)) as ItemViewModel);
还使用“选择”而不是“Where 不起作用”。
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
}
}
这可能是我忽略的一些愚蠢的事情,但如果有人知道解决方案,那就太好了!
谢谢。
最佳答案
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
在您的示例中,它将是:
// 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);
关于使用 Select 或Where 的 C# 谓词不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13539095/