I’m having a misunderstanding problem with this use of Linq Query
I do have this Entity
class Content
{
public string Type = "X";
public string Name;
public int? Owner;
}
and a List list
the list contains 2 members both equals by type except by the Name and Owner(one is null and the other is not).
So i tried do query to find the Content with an specific Owner, if none is found, return the other the query used below:
int? owner = 1;
var result = (
from c in list
where c.Type == "X" && c.Owner == owner
select c
).FirstOrDefault(c => c.Type == "X" && c.Owner == (int?)null);
but the resulting member is returning null. What should be the correct statement for this query?
You’re applying two filters here. The
whereclause will only return values which have the given owner – and then the predicate in theFirstOrDefaultclause will only consider values which have no owner.I suggest you use:
Using
OrderByDescendingwill put any value with a null owner after a value with a non-null owner, so when you take the first result it will get one with an owner if it’s present.