如何问“是否存在一个完全满足条件的元素"?在LINQ吗? [英] How to ask "Is there exactly one element satisfying condition" in LINQ?

查看:46
本文介绍了如何问“是否存在一个完全满足条件的元素"?在LINQ吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,以编程方式询问此序列中是否确实有一个元素满足X条件?"的首选方法是什么?使用Linq吗?

Quick question, what's the preferable way to programmaticaly ask "Is there exactly one element in this sequence that satisfies X condition?" using 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);

类似的事情可以通过以下方式完成:

something like this can be done with:

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

但这有点笨拙.

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

I suppose I could roll my own extension method, but this seems to be a common pattern in my code and I want to make sure there's a good clean way to do it. Is there a way using the built-in LINQ methods?

推荐答案

您可以这样做:

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

在多次匹配的情况下,这将防止count不必要地枚举较大的序列.

Which will prevent count from enumerating a large sequence unnecessarily in the event of multiple matches.

这篇关于如何问“是否存在一个完全满足条件的元素"?在LINQ吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆