C# 在插入/添加之前,如何在C中检查列表的内容?谓词类用于什么?

C# 在插入/添加之前,如何在C中检查列表的内容?谓词类用于什么?,c#,list,C#,List,使用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<i

使用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的项。对于它的工作原理有点困惑。

您也可以使用方法


谓词是一个返回bool的委托,它允许您查找与某个条件匹配的项,这就是为什么要将要检查的项作为参数传递给它的原因。

这对于集合类型很有用,它不允许重复项,只是默默地忽略它们。

对于您的场景,您应该在List类上使用Contains方法

那么你可能会问,存在的目的是什么?Contains方法使用对象上的Equals方法来确定要检查的项是否包含在列表中。仅当类已重写Equals方法进行相等检查时,此操作才有效。如果没有,那么你认为相等的两个不同的例子将不被认为是平等的。< /P> 除此之外,您可能希望使用Equals方法提供的不同逻辑。现在,确定列表中是否有内容的唯一方法是自己迭代它,或者编写自己的EqualityComparer来检查实例的相等性

因此,list类所做的就是公开一些方法,比如Exists,这样您就可以在为您进行样板迭代时,以一种简单的方式提供您自己的逻辑

范例

假设你有一个狗的类型列表。现在,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" };
现在,如果您填写上面的谓词,该方法将如下所示

public bool Exists(Dog other) {
    foreach (Dog item in Items) {
        if (item.Name == other.Name && item.Owner == other.Owner)
            return true;
    }

    return false;
}

非常不公正的信息。哇,你的回答最终解决了我的问题。HAHAST可能是一个更好的解决方案,尽管HASSET。Addio如果该项已经在集合中,则返回false,因此它不太安静。MMM,我可能不得不将其视为另一个选项。哈希特集只在等号/ GethHAc码被重写时起作用,所以这是要考虑的。对于自定义类,是的,您需要一个好的Equals/GetHashCode覆盖。对于Int32,不用担心。
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" };
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;
}