0

I need to use Equals method or something similar instead of using Contains method because i want to search in database for the exact values in selectedDeviceTypeIDs array not any of it.

IEnumerable<Guid> selectedDeviceTypeIDs = DeviceTypeIDs
    .Split(',')
    .Select( Guid.Parse )
    .AsEnumerable();

query = query
    .Where( j =>
        j.HospitalDepartments.Any( jj =>
            jj.Units.Any( m =>
                m.Devices.Any( w =>
                    selectedDeviceTypeIDs.Contains( w.DeviceTypeID )
                )
            )
        )
    );

Here is my full code

public HttpResponseMessage GetAvailableHospitalsByAjax(System.Guid? DirectorateOfHealthID = null, System.Guid? UnitTypeID = null, string DeviceTypeIDs = null)
{
    Context db = new Context();
    var query = db.Hospitals.AsQueryable();

    if (DeviceTypeIDs != null)
    {
        IEnumerable<Guid> selectedDeviceTypeIDs = DeviceTypeIDs.Split(',').Select(Guid.Parse).AsEnumerable();
        query = query.Where(j => j.HospitalDepartments.Any(jj => jj.Units.Any(m => m.Devices.Any(w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID)))));
    }

    if (UnitTypeID != null)
    {
        query = query.Where(j => j.HospitalDepartments.Any(www => www.Units.Any(u => u.UnitTypeID == UnitTypeID)));
    }

    if (DirectorateOfHealthID != null)
    {
        query = query.Where(h => h.DirectorateHealthID == DirectorateOfHealthID);
    }

    query = query.Where(j => j.HospitalDepartments.Any(u => u.Units.Any(d => d.Devices.Any(s => s.Status == Enums.DeviceStatus.Free)))
    && j.HospitalDepartments.Any(hd => hd.Units.Any(u => u.Beds.Any(b => b.Status == Enums.BedStatus.Free))));

    var list = query.ToList();
    return Request.CreateResponse(HttpStatusCode.OK, list);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Alex
  • 195
  • 3
  • 3
  • 12

1 Answers1

0

Your problem is not Contains() but with the Any() method used in your query which will return true immediately after it finds a device whose DeviceTypeID is in the provided selectedDeviceTypeIDs list.

If you need to check if all the devices of a unit match all the items in the list, you could use:

query = query
.Where(j =>
    j.HospitalDepartments.Any(jj =>
        jj.Units.Any(m =>
            m.Devices.All(
                w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID))
            &&
            selectedDeviceTypeIDs.All(
                g => m.Devices.Select(d => d.DeviceTypeID).Contains(g))
        )
    )
);

Note that if you have duplicate items in the selectedDeviceTypeIDs but not in the Devices of the Unit, it will still return true.

granit
  • 570
  • 4
  • 9