jeanre
jeanre

Reputation:

Linq2SQL check if item is null

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

Upvotes: 0

Views: 378

Answers (2)

crowleym
crowleym

Reputation: 2552

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)))

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

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) {
   // ...
}

Upvotes: 2

Related Questions