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

时间:2012-10-10 10:55:34

标签: c# list

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

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

我的班级

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
        }
    }

Iniial情况

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

此对象已添加到列表中。

第二次

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

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

任何建议。

3 个答案:

答案 0 :(得分:3)

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
};

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

答案 1 :(得分:0)

您可以使用.Contains方法,但需要为对象实现Equal方法。

检查此链接:

http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx

答案 2 :(得分:0)

试试这个

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

存在返回bool

相关问题