the problem in short
we have a lambda expression used in the Where clause, which is not returning the "expected" result.
quick summary
in the analysisObjectRepository object, there are certain objects which also contain the parent relationship in a property named Parent. we are querying this analysisObjectRepository to return some objects.
detail
what the code below supposed to do is, returning the root, the first children (immediate children) and grandchildren of a specific object containing the ID value.
in the code below, common sense says that all the results which makes any of the 3 seperate OR conditions true should be returned as in the results.
List<AnalysisObject> analysisObjects =
analysisObjectRepository
.FindAll()
.Where(x => x.ID == packageId ||
x.Parent.ID == packageId ||
x.Parent.Parent.ID == packageId)
.ToList();
but the above code only returns the children and grandchildren, while not returning the root objects (with a null Parent value) which make the
x.ID == packageId
condition true.
only objects which make the second
x.Parent.ID == packageId
and third
x.Parent.Parent.ID == packageId
clauses are returned.
If we only write the code to return the root object with the below code, it is returned, so we are totally sure that analysisObjectRepository contains all the objects
List<AnalysisObject> analysisObjects =
analysisObjectRepository
.FindAll()
.Where(x => x.ID == packageId )
.ToList();
However, when we rewrite it as a delegate, we get the expected result, returning all the expected objects.
List<AnalysisObject> analysisObjects =
analysisObjectRepository
.FindAll()
.Where(delegate(AnalysisObject x)
{
return
(x.ID == packageId) ||
(x.Parent != null && x.Parent.ID == packageId) ||
(x.Parent != null &&
x.Parent.Parent != null &&
x.Parent.Parent.ID == packageId); })
.ToList();
question
Are we missing something in the lambda expression? it is a really simple 3 part OR condition and we think that any object that makes any of the three conditions true should be returned. we suspected that the root object having a null Parent value might cause a problem but couldn't figure it out exactly.
any help would be great.
analysisObjectRepository
aList<AnalysisObject>
? If so, the call toFindAll
is unnecessary. – WidenIQueryable
can make all the difference here. – Widen