我有一种方法,应该检查集合中是否有一个元素对于某些谓词(以 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/