c# - LINQ C# 集合中的唯一元素

标签 c# linq collections predicate

我有一种方法,应该检查集合中是否有一个元素对于某些谓词(以 Func 形式给出)成立。

public bool ExistsUnique(Func<T, bool> p)
    {
        var tempCol = from i in MyCollection where p(i) select i;  
        return (tempCol.Count() == 1);
    }

问题在于,当第二个元素也适用于谓词时 找到(例如集合中存在两个相同的字符串)计数仍然为 1。这意味着它要么覆盖第一个元素,要么从不添加第二个元素,因为它已经存在。

关于如何修复此方法有什么想法吗? 谢谢 /彼得

最佳答案

您可以使用 LINQ 提供的 Single() 方法,如下所示:

public bool ExistsUnique(Func<T, bool> p)
{
    try
    {
        var temp = myCollection.Single(x => p(x));
    }
    catch(Exception e)
    {
        // log exception
        return false;
    }

    return true;
}

"Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists."

来自http://msdn.microsoft.com/en-us/library/bb535118.aspx

编辑

为了避免引发异常,您还可以使用 SingleOrDefault() 方法:

public bool ExistsUnique(Func<T, bool> p)
{
    return myCollection.SingleOrDefault(x => p(x)) != null;
}

关于c# - LINQ C# 集合中的唯一元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8044426/

相关文章:

java - 带有 iterator.next 的空指针

c# - 将 Entity Framework 与两个单独的数据库(开发和生产)一起使用

c# - Outlook VSTO 未在 NewMailEx 事件上触发?

c# - MVVM 光 4 RTM : Where are the templates?

c# - 使用 LINQ .ExecuteQuery 调用存储过程以返回非映射字段

c# - 自定义列表和字符串列表的区别

java - 从 map 返回一组值

c# - 在 Windows 8 应用程序中使用 MessageBinder.SpecialValues 不起作用?

.Net Linq 到 JSON 与 Newtonsoft JSON 库

Java随机插入集合