LINQ: Use FirstOrDefault to return an member or another

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?

Upvotes: 3

Views: 297

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500185

You're applying two filters here. The where clause will only return values which have the given owner - and then the predicate in the FirstOrDefault clause will only consider values which have no owner.

I suggest you use:

var value = list.Where(c => c.Type == "X" && 
                            (c.Owner == null || c.Owner == owner))
                .OrderByDescending(c => c.Owner)
                .FirstOrDefault();

Using OrderByDescending will 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.

Upvotes: 5

Related Questions