I have a query like below. anyone have idea why the ?: parts are always return false values although there is item contains in LIST. Or anyone have better idea to write this query, feel free to reply here. thanks.
List EList = new List();
EList.Add(new EmployeeInfo(1, "a1", "b1"));
EList.Add(new EmployeeInfo(2, "a2", "b2"));
List OList = new List();
OList.Add(new EmployeeInfo(1, "a1", "b1"));
OList.Add(new EmployeeInfo(2, "a2", "b2"));
OList.Add(new EmployeeInfo(3, "aa2", "bb2"));
var results = (
from e in b
select new
{
Id = e.ID,
Name = e.Name,
Email = e.Email,
IS_Elist = (EList.Contains(e))?true:false,
IS_Olist = (OList.Contains(e)) ? true : false,
}
).ToList();
First you can simplify your query –
expression ? : true : falseis equivalent to justexpressionand we get the following.This should and will definitely yield
trueif an item frombis contained inEListorOList. If you always getfalsethis means thatEListandOListdo not contain any items fromb. Remember that you are probably doing a comparison of references and thereforewill usually yield
false.I guess you actually intended a comparison by
ID.The alternative solution is to implement
IEquatable<T>onEmployeeInfoor overridingEquals(),GetHashCode()and the equality operator. You should take care that all your implementations yield consistent results or you will end with a lot of confusion why for exampleObject.Equals()and the equality operator yield different results.