0

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 Answers 2

2
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) {
   // ...
}
Sign up to request clarification or add additional context in comments.

9 Comments

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 added that option too. Both are effectively the same. Refresh to see.
in SQL I would do this WHERE USerId = ISNULL(@UserId,UserId)
It should work. There's no problem in chaining Where clauses. They act like AND.
|
0
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)))

Comments