gpt4 book ai didi

c# - 添加之前检查对象是否已存在于列表中

转载 作者:行者123 更新时间:2023-11-30 22:24:21 26 4
gpt4 key购买 nike

我正在开发以 .net 2.0 作为框架的 win-form 应用程序。我有一个类列表,我想在将其添加到列表之前检查该对象是否已经存在。我知道我可以使用 linq 的 .Any 来做到这一点,但它在我的情况下不起作用。我不能使用 .contains 因为对象不会相同,因为它有很多属性,所以我留下了一个独特的属性来检查它是否已经添加,但它不起作用代码:

bool alreadyExists = exceptionsList.Exists(item =>
item.UserDetail == ObjException.UserDetail
&& item.ExceptionType != ObjException.ExceptionType) ;

我的类(class)

public class AddException
{
public string UserDetail{ get; set; }
public string Reason { get; set; }
public Enumerations.ExceptionType ExceptionType { get; set; }

}
public class Enumerations
{
public enum ExceptionType
{
Members = 1,
Senders =2
}
}

初始情况

AddException objException = new AddException
{
Reason = "test",
UserDetail = "Ankur",
ExceptionType = 1
};

此对象已添加到列表中。

第二次

AddException objException = new AddException
{
Reason = "test 1234",
UserDetail = "Ankur",
ExceptionType = 1
};

这不应该被添加到列表中,但是 .Exist 检查失败并且它被添加到列表中。

任何建议。

最佳答案

Exists已经返回 bool 而不是对象,因此最后的空检查不起作用。

bool alreadyExists = exceptionsList.Exists(item =>
item.UserDetail == ObjException.UserDetail
&& item.ExceptionType == ObjException.ExceptionType
);

重要的是,你必须改变

item.ExceptionType != ObjException.ExceptionType

item.ExceptionType == ObjException.ExceptionType

因为您想知道是否有与 UserDetailExceptionType 相等的项。

另请注意,您不应使用其 int 值初始化 Enums。所以改变

AddException objException = new AddException
{
Reason = "test 1234",
UserDetail = "Ankur",
ExceptionType = 1
};

AddException objException = new AddException
{
Reason = "test 1234",
UserDetail = "Ankur",
ExceptionType = Enumerations.ExceptionType.Members
};

(顺便说一句,那甚至不应该编译)

关于c# - 添加之前检查对象是否已存在于列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12817694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com