LINQ equal instead of Contains

2020-02-07 11:24发布

I need to use equal instead of Contains. I have an array of codes called selectedDeviceTypeIDs i assume it has two codes {1,2}

I need get result from the query if Devices ids are exactly {1,2} so i have replace selectedDeviceTypeIDs.Contains with selectedDeviceTypeIDs.equal or something like that ...

m => m.Devices.Any(w => selectedDeviceTypeIDs.Contains(w.DeviceTypeID)

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

标签: c# sql linq
3条回答
再贱就再见
2楼-- · 2020-02-07 11:27

You need to check if the selectedDeviceTypeIDs contains every device, and that every device contains selectedDeviceTypeIDs. You could use this:

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))
        )
    )
);
查看更多
Melony?
3楼-- · 2020-02-07 11:31

Option 1:

If you care about the Order of the items, use SequenceEqual extension method. This will return false, even if the collection has the items but in different order

m => m.Devices.Any(w => selectedDeviceTypeIDs.SequenceEqual(w.DeviceTypeID)

Option 2:

If you don't care about the order , use All extension method. This will return true, if the items in both collections are same irrespective of the order.

m => m.Devices.Any(w => selectedDeviceTypeIDs.All(w.DeviceTypeID.Contains)
查看更多
家丑人穷心不美
4楼-- · 2020-02-07 11:44

Use !.Except().Any() to make sure m.Devices doesn't contains any DeviceTypeID not present in selectedDeviceTypeIDs

query = query.Where(j => j.HospitalDepartments.Any(jj => jj.Units
.Where(m => !m.Devices.Select(w => w.DeviceTypeID).Except(selectedDeviceTypeIDs).Any())));
查看更多
登录 后发表回答