c# - 如何在 LINQ 中询问 "Is there exactly one element satisfying condition"?

标签 c# .net linq

快速提问,以编程方式询问“此序列中是否恰好有一个元素满足 X 条件?”的最佳方式是什么?使用 Linq?

// Pretend that the .OneAndOnlyOne() method exists
int[] sequence = new int[] { 1, 1, 2, 3, 5, 8 };
Assert.IsTrue(sequence.OneAndOnlyOne(x => x == 2);
Assert.IsFalse(sequence.OneAndOnlyOne(x => x == 1);

这样的事情可以用:

sequence.SingleOrDefault(x => x == 2) != null;

但这有点笨拙。

我想我可以推出我自己的扩展方法,但这似乎是我代码中的常见模式,我想确保有一个很好的干净方法来做到这一点。有没有办法使用内置的 LINQ 方法?

最佳答案

你可以这样做:

bool onlyOne = source.Where(/*condition*/).Take(2).Count() == 1

这将防止计数在多次匹配的情况下不必要地枚举大序列。

关于c# - 如何在 LINQ 中询问 "Is there exactly one element satisfying condition"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993253/

相关文章:

c# - 通过查询调用存储过程并在没有输出参数的情况下在C#中获取返回值

c# - AppHarbor 上的新 MVC4 应用程序出现错误 : Unable to find the requested .Net Framework Data Provider。它可能没有安装

c# - 如何在 .NET 3.5 中获取 CSIDL_COMMON_DOCUMENTS 的路径?

asp.net - 从 ASP.NET Dev Server 移动到 IIS 后出现 "An attempt to attach an auto-named database for file *FileName* failed."错误

Linq GroupBy 如果它们被其他键分隔,则不合并具有相同键的分组

c# - 在 C# for mysql 中使用 Checkbox 加入索引进行搜索

c# - 以编程方式抑制 Windows 警报

.net - 单元测试构造函数时的多个断言?

c# - 将此 LINQ 表达式转换为 Lambda

c# - 统一解析嵌套的json