tags:

views:

97

answers:

2

Hi all

 foreach (var incident in new DataAccess.IncidentRepository().GetItems().Where(
                    i => (startDate == null || i.IncidentDate >= startDate)
                    && (endDate == null || i.IncidentDate <= endDate)
                    && (shiftId == null || i.ShiftId == shiftId)
                    && (processAreaId == null || i.ProcessAreaId == processAreaId)
                    && (plantId == null || i.PlantId == plantId)))

is there a way I can i.PlantId == plantId not to get added if plantId is null?

Thanks

+2  A: 
var incident in new DataAccess.IncidentRepository().GetItems().Where(
                    i => i.IncidentDate >= startDate 
                    && i.IncidentDate <= endDate 
                    && i.ShiftId == shiftId 
                    && i.ProcessAreaId == processAreaId
                    && (plantId == null || i.PlantId == plantId)))

Alternatively, you could:

var incidents = new DataAccess.IncidentRepository().GetItems().Where(
                    i => i.IncidentDate >= startDate 
                    && i.IncidentDate <= endDate 
                    && i.ShiftId == shiftId 
                    && i.ProcessAreaId == processAreaId));

if (plantId != null)
    incidents = incidents.Where(i => i.PlantId == plantId);

foreach (var incident in incidents) {
   // ...
}
Mehrdad Afshari
That makes no sense i.PlantId comes for the database plantId is the parameter passed into the method.
so basicly if plantId == null then i.PlantId should not be added to the where clause.
I dont think this will work.
I added that option too. Both are effectively the same. Refresh to see.
Mehrdad Afshari
in SQL I would do thisWHERE USerId = ISNULL(@UserId,UserId)
It should work. There's no problem in chaining Where clauses. They act like AND.
Mehrdad Afshari
+1 for converting common SQL dynamic parameter "trick" into Linq. ;)
J. Steen
Thats where the problem comes in I will need to have like 50 if statements which is not what I wanted to do. I tought there might be a easy way
The first query is effectively like your `ISNULL` query. The second doesn't send the parameter to the server at all if it's null.
Mehrdad Afshari
So choose the first option. It's the most succinct way out there.
Mehrdad Afshari
A: 
var incident in new DataAccess.IncidentRepository().GetItems().Where(
                    i => i.IncidentDate >= startDate 
                    && i.IncidentDate <= endDate 
                    && i.ShiftId == shiftId 
                    && i.ProcessAreaId == processAreaId
                    && object.Equals(i.PlantId, plantId)))
crowleym
It's not what the OP wants...
Mehrdad Afshari