Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ c集合中的唯一元素_C#_Linq_Collections_Predicate - Fatal编程技术网

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

C# LINQ c集合中的唯一元素,c#,linq,collections,predicate,C#,Linq,Collections,Predicate,我有一个方法,用来检查集合中是否有一个元素对于作为Func给定的某个谓词为true public bool ExistsUnique(Func<T, bool> p) { var tempCol = from i in MyCollection where p(i) select i; return (tempCol.Count() == 1); } 问题是当第二个元素对谓词也成立时 例如,在一个集合中存在两个相同的字符串,但计数

我有一个方法,用来检查集合中是否有一个元素对于作为Func给定的某个谓词为true

public bool ExistsUnique(Func<T, bool> p)
    {
        var tempCol = from i in MyCollection where p(i) select i;  
        return (tempCol.Count() == 1);
    }
问题是当第二个元素对谓词也成立时 例如,在一个集合中存在两个相同的字符串,但计数仍然为1。这意味着它要么重写第一个元素,要么从不添加第二个元素,因为它已经存在

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

你确定tempCol已经完全通过我的收集循环了吗? Count是一个强制完成循环的方法还是一个懒惰的方法


例如tempCol.ToList.Count是否给出了正确的结果?

肯定还有其他问题。我怀疑你的谓词。例如,这将返回一个计数2,如预期的那样:

        List<string> MyCollection = new List<string>()
        {
            "hello",
            "hello"
        };
        var tempCol = from i in MyCollection where i == "hello" select i;
        int count = tempCol.Count();
您可以使用LINQ提供的单一方法,如下所示:

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

    return true;
}

此实现将使您不必实际枚举整个集合,从而节省一些执行时间

public bool ExistsUnique(Func<T, bool> p)
{
    return MyCollection.Where(i => p(i)).Take(2).Count() == 1;
}

Take2将计数限制为仅列举满足条件的前两个。

我试着说pi | |!pi,它在集合中添加了所有元素,一次没有重复,只是为了检查它是否确实遍历了它所做的所有元素。我想你可能是对的。尽管谓词my_set.ExistsUniques=>s.EqualsHello,我认为还可以。我在Exists方法中使用了完全相同的方法,只是检查是否至少有一个元素为true,这是有效的。这可能是我写pi的方式吗?@PNS:看看我最新的答案。我不认为问题在于你调用它的方式。现在我真的很困惑,与你的方法和我自己的方法的唯一区别是,你的ExistsUnique方法接受string,bool,而我的方法接受t,bool,但它仍然应该工作。是吗?我想它的答案可能会对你有所帮助。这是个好主意!我试过了,虽然我仍然遇到同样的问题,但它返回true,即使我尝试添加两个相同的字符串。当不需要异常时,抛出异常的速度非常慢,当有简单的方法可以毫无例外地做同样的事情时,可能需要小心使用此技术。添加了一个毫无例外的选项,但也保留了例外。这两个选项在我看来都是可行的,取决于期望的结果。@shuniar我不同意,但-1被删除。顺便说一句,在回复时,如果你在评论中加上他们的名字,人们会更快地知道
public bool ExistsUnique(Func<T, bool> p)
{
    return myCollection.SingleOrDefault(x => p(x)) != null;
}
public bool ExistsUnique(Func<T, bool> p)
{
    return MyCollection.Where(i => p(i)).Take(2).Count() == 1;
}