Reputation: 11356
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>
Upvotes: 1
Views: 104
Reputation: 49985
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 Wales
would have a corresponding value of NSW
. The entry that reads All Sites
would have a value of null
. So you could change your query to:
public object GetMyStuff(string loc)
{
var dataSetB = db.Data
.Where(j => loc == null || j.Location1.Description == loc);
}
Logical shortcutting applies in the expression, so the j.Location1.Description
will 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 Sites
for a bunch of reasons.
Upvotes: 1
Reputation: 41
If you want all the results, the filter should accept all entries, so the correct syntax is I think:
var dataSetB = db.Data
.Where(j => loc == 'All Sites' || j.Location1.Description.Equals(loc));
Upvotes: 0
Reputation: 3154
Not entirely sure this will work:
var dataSetB = db.Data
.Where(j => loc != 'All Sites' ? j.Location1.Description.Equals(loc) : true);
Upvotes: 1
Reputation: 1369
I dont know that you want to use LINQ for the "All Sites" case.
Check to see if the Dropdown Value == "All sites".
If true, use the entire data set.
If false, execute the LINQ query.
Upvotes: 0
Reputation: 79969
Use if.. else
instead like this:
var dataSetB = db.Data;
if(dropdownlist.SelectedIndex != 0)
dataSetB = dataSetB.Where(j => j.Location1.Description.Equals(loc));
//loc should be the dropdown list value
Upvotes: 0
Reputation: 2583
Try this
var dataSetB = db.Data;
if (loc != 'All Sites')
dataSetB = dataSetB
.Where(j => loc != 'All Sites' && j.Location1.Description.Equals(loc));
Upvotes: 0
Reputation: 16038
Just translate your query to LINQ using the OR
operator:
var dataSetB = db.Data
.Where(j => loc == 'All Sites'
|| j.Location1.Description.Equals(loc));
Upvotes: 0