tags:

views:

63

answers:

2

I have a basic tag searching system setup, each tag has a field for an ID for a category. Some tags will have no category.

So in my methods, I just pass a string through to define the category to get in a list.

public IQueryable<Tag> List(string category)
{
 //...
}

I want to return tags that have no category if nothing is passed through. This works if I write the query like this...

return t from db.Tags
       where t.Category == null
       select t;

However then I need two queries (one if it is null, one if it is not) I was wondering if I can do this all in one query for simplification.

The current query is ...

return t from db.Tags
       where t.Category.Name == name
       select t;
A: 

I think this is the best way:

if(name == null)
    return t from db.Tags
           where t.Category.Name == null
           select t;
else
    return t from db.Tags
           where t.Category != null && t.Category.Name == name
           select t;

You don't want execute a more complicated query on the DB server then needed. If you combine the 2, which is probably possible, the query will also contain an ISNULL check for name.

Sander Rijken
+1  A: 
db.Tags
.Where(t=> Category==null?t.Category==null:t.Category.Name==Category);
Alexander Taran