[英]How do you check a list in C# for contents before an insert/add? What is the predicate class for?
使用List类时,我注意到我正在寻找的布尔值是:
if(lstInts.Exists(x)){...}
X是T的谓词,与lstInts相同。 对于为什么在这种情况下您不能通过int以及为什么X的类型不是T类型,我感到困惑。
我正在测试的示例:
List<int> listInt = new List<int>();
int akey = Convert.toInt32(myMatch.Value);
Predicate<int> pre = new Predicate<int>(akey); //akey is not the correct constructor param.
if(listInt.Exists(pre)){
listInt.add(akey);
}
是否有附加谓词步骤的理由,或者...如果我不正确地讨论逻辑?
我还注意到谓词结构没有采用类型T的项。对于这应该如何工作有些困惑。
您也可以使用Contains()方法
List<int> listInt = new List<int>();
int akey = Convert.toInt32(myMatch.Value);
if(listInt.Contains(akey)){
listInt.add(akey);
}
或者替代使用Any()
if(listInt.Any(I => I == akey)) {
// Do your logic
}
Predicate<T>
是一个委托(返回bool
),它使您可以找到符合某些条件的项目(这就是为什么要检查的项目作为参数传递给它的原因)。
这对于HashSet<T>
集合类型将是一个很好的用途,该类型不允许重复(只是默默地忽略它们)。
好了,对于您的方案,您应该在List
类上使用Contains
方法。
那么,您可能会问存在的目的是什么? 好吧, Contains
方法在对象上使用Equals
方法来确定您要检查的项目是否包含在列表中。 仅当该类已重写Equals
方法以进行相等性检查时,此方法才有效。 如果还没有,那么您认为相等的某事的两个单独实例将不会被视为相等。
除此之外,也许您想使用Equals
方法提供的不同逻辑。 现在,确定列表中是否包含某些内容的唯一方法是自己迭代或编写自己的EqualityComparer来检查实例的相等性。
因此,列表类的作用是公开一些类似于Exists
方法,以便您可以轻松地提供自己的逻辑,同时为您进行样板迭代。
例
考虑您有一个Dog
类型列表。 现在,dog类已经覆盖了Equals
方法,因此无法检查一条狗是否与另一只相等,但是它们具有有关该狗的一些信息,例如它的名称和所有者。 所以考虑以下
List<Dog> dogs = new List<Dog> {
new Dog { Name = "Fido", Owner = "Julie" },
new Dog { Name = "Bruno", Owner = "Julie" },
new Dog { Name = "Fido", Owner = "George" }
};
Dog fido = new Dog { Name = "Fido", Owner = "Julie" };
List.Contains(fido)
Equals
方法) List.Exists(x => fido.Name == x.Name && fido.Owner == x.Owner)
如果要查看列表类的源代码,您可能会看到类似这样的内容。
public bool Exists(Predicate<Dog> predicate) {
foreach (Dog item in Items) {
if (predicate(item))
return true;
}
return false;
}
现在,如果您填写上面的谓词,该方法将如下所示
public bool Exists(Dog other) {
foreach (Dog item in Items) {
if (item.Name == other.Name && item.Owner == other.Owner)
return true;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.