I am working on win-form app that has .net 2.0 as framework. I have a list of an class in which i would like to check if the object already exist before adding it in list. I know i can use .Any of linq to do this but it does not work in my situation. I can not use .contains since the object will not be same as it has lot of properties , so I am left with a unique property to check if it is already added,but it is not working Code:
bool alreadyExists = exceptionsList.Exists(item =>
item.UserDetail == ObjException.UserDetail
&& item.ExceptionType != ObjException.ExceptionType) ;
My 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
}
}
Iniial situation
AddException objException = new AddException
{
Reason = "test",
UserDetail = "Ankur",
ExceptionType = 1
};
this object is added in list.
Second time
AddException objException = new AddException
{
Reason = "test 1234",
UserDetail = "Ankur",
ExceptionType = 1
};
this should not be getting added in the list , but the .Exist check is failing and it is getting added in the list.
Any suggestions.
Existsreturns already thebooland not an object, so your null check at the end doesn’t work.The important part is, you have to change
to
since you want to know if there are items which are equal by
UserDetailandExceptionType.Also note that you should not initialize
Enumswith their int-value. So changeto
(By the way, that should not even compile)