简体   繁体   中英

Linq to Generic list C# Data Filtering issue

I am having a problem with following linq query in my c# code. I want to exclude data that has jobChangeTypeId Unallocate or Delete but its bringing them in the resultset.

foreach (EmployeejobAudit empjobAudit in list)
{
     int iEmployeeServiceId = empjobAudit.EmployeeServiceId;

     PushNotificationData.jobAuditRow[] jobAuditList = empjobAudit.jobAuditList;

     var jobCallQuery = (from job in jobAuditList
                         where ((from dc in dataset.jobCall select dc.jobId).Contains(job.jobId)) && 
                        ( job.jobChangeTypeId != (int) Common.jobChangeTypeId.Unallocate  || job.jobChangeTypeId != (int) Common.jobChangeTypeId.Delete)                                   
                         select job).Distinct();

     if (jobCallQuery.Any())
     {
         foreach (var item in jobCallQuery)
         {
             System.Diagnostics.Debug.WriteLine("jobId {0}  Employee ServiceID {1} jobChange Type ID {2}", item.jobId, item.EmployeeServiceId, item.jobChangeTypeId);
         }
     }
}

It's an AND not an OR if you want to exclude both of them

foreach (EmployeejobAudit empjobAudit in list)
{
     int iEmployeeServiceId = empjobAudit.EmployeeServiceId;

     PushNotificationData.jobAuditRow[] jobAuditList = empjobAudit.jobAuditList;

     var jobCallQuery = (from job in jobAuditList
                         where ((from dc in dataset.jobCall select dc.jobId).Contains(job.jobId)) && 
                        ( job.jobChangeTypeId != (int) Common.jobChangeTypeId.Unallocate && job.jobChangeTypeId != (int) Common.jobChangeTypeId.Delete)                                   
                         select job).Distinct();

     if (jobCallQuery.Any()) //Useless because the following foreach will do it for you, but you can test if != null 
     {
         foreach (var item in jobCallQuery)
         {
             System.Diagnostics.Debug.WriteLine("jobId {0}  Employee ServiceID {1} jobChange Type ID {2}", item.jobId, item.EmployeeServiceId, item.jobChangeTypeId);
         }
     }
}

You're doing || instead of && . The problem is that when using || one of the two expressions will always be true, thus be included.

This:

job.jobChangeTypeId != (int) Common.jobChangeTypeId.Unallocate  
|| job.jobChangeTypeId != (int) Common.jobChangeTypeId.Delete

Needs to be changed to this:

job.jobChangeTypeId != (int) Common.jobChangeTypeId.Unallocate  
&& job.jobChangeTypeId != (int) Common.jobChangeTypeId.Delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM