views:

18

answers:

2

If I have a query like this:

String Category = HttpContext.Current.Request.QueryString["Product"].ToString();

IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                                           where file.Type_ID == 8
                                                                && file.Category == Category 
                                                           select file;

Is there a way to make this LINQ Query so that I do no use the line file.Category == Category if Category is null or empty?

+1  A: 

This might not be exactly what you wanted but will render the same result:

String Category = HttpContext.Current.Request.QueryString["Product"].ToString();

IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                     where file.Type_ID == 8
                                     && (string.IsNullOrEmpty(Category) || file.Category == Category)
                                     select file;
Sani Huttunen
Sani, I'm thinking that the OP is concerned where "Category" is null or empty, not file.Category. If so, I think your solution would exclude some items that should be included.
itsmatt
You're correct... Changed...
Sani Huttunen
+3  A: 

How about don't add that where unless you need to?

IQueryable<ItemFile> pressReleases = from file in connection.ItemFile
                                     where file.Type_ID == 8
                                     select file;

if(!string.IsNullOrEmpty(Category)) {
    pressReleases = pressReleases.Where(file => file.Category == Category);
}

This works because LINQ queries are composable with deferred execution, so this filter is still part of the final TSQL.

Marc Gravell
Thank you! I appreciate the help!
RandomBen