i am trying to design a LINQ query that filters on a specific location. In my UI dropdown list, that dropdown has the first entry as ‘All Sites’. So when the query see’s ‘All Sites’ as the value, it should not perform the filter. This may not make much sense but this is how i used to do it in SQL..
select * from table
where ((location = @loc and @loc is not null) or (@loc is null))
this is how i am trying to do it in LINQ.
var dataSetB = db.Data
.Where(j => loc != 'All Sites' && j.Location1.Description.Equals(loc));
The problem is that when the user selects ‘All Sites’ – no result are returned when i would be expecting all results not filtered by location.
Does anyone know how to accomplish this in one LINQ statement?
example dropdown..
<All Sites>
<Sydney>
<New York>
<London>
Your dropdown wouldn’t normally have just text, it will normally be bound to text/value pairs. So your text entry that reads
New South Waleswould have a corresponding value ofNSW. The entry that readsAll Siteswould have a value ofnull. So you could change your query to:Logical shortcutting applies in the expression, so the
j.Location1.Descriptionwill only be compared if the passed loc value is not null.Using neutral location values is important – you don’t really want to be comparing the literal text
All Sitesfor a bunch of reasons.