[英]LINQ c# unique element in collection
我有一种方法应该检查集合中是否确实有一个元素对某些谓词(给出为Func)成立。
public bool ExistsUnique(Func<T, bool> p)
{
var tempCol = from i in MyCollection where p(i) select i;
return (tempCol.Count() == 1);
}
这样做的问题是,当找到对谓词也成立的第二个元素时(例如,集合中存在两个相同的字符串),计数仍为1。这意味着它要么覆盖第一个元素,要么从不添加第一个元素。第二,因为它已经存在。
关于如何解决此方法的任何想法? thx /彼得
您可以像这样使用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;
}
“返回序列中唯一满足指定条件的元素,如果存在多个这样的元素,则引发异常。”
从http://msdn.microsoft.com/en-us/library/bb535118.aspx
编辑
为了避免引发异常,您还可以使用SingleOrDefault()
方法:
public bool ExistsUnique(Func<T, bool> p)
{
return myCollection.SingleOrDefault(x => p(x)) != null;
}
您确定tempCol
已完全遍历MyCollection
吗? 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();
我也怀疑这就是您所说的方式。 以下工作(返回false
):
static List<string> MyCollection = new List<string>()
{
"hello",
"hello"
};
static bool ExistsUnique(Func<string, bool> p)
{
var tempCol = from i in MyCollection where p(i) select i;
return tempCol.Count() == 1;
}
static void DoIt()
{
bool isUnique = ExistsUnique((s) => s.Equals("hello"));
Console.WriteLine(isUnique);
}
该实现将使您不必真正枚举整个集合,从而节省了一些执行时间。
public bool ExistsUnique(Func<T, bool> p)
{
return MyCollection.Where(i => p(i)).Take(2).Count() == 1;
}
Take(2)
将Count
限制为仅枚举满足条件的前两个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.