【问题标题】:How to use the Exact array value instead of Contains [duplicate]如何使用精确数组值而不是包含 [重复]
【发布时间】:2017-04-15 18:55:21
【问题描述】:

我需要使用 Equals 方法或类似方法,而不是使用 Contains 方法,因为我想在数据库中搜索 selectedDeviceTypeIDs 数组中的确切值,而不是其中的任何一个。

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

这是我的完整代码

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

【问题讨论】:

  • 我不清楚你的问题是什么。 “精确值”是什么意思?您能否举例说明内容以及您期望的结果?
  • 旁注 - .AsEnumerable() 是多余的 - 它已经是 IEnumerable
  • 你需要加入。 from record in db from x in arr where ... select ...

标签: c# sql-server entity-framework linq


【解决方案1】:

您的问题不是Contains(),而是您的查询中使用的Any() 方法,该方法将在找到DeviceTypeID 在提供的selectedDeviceTypeIDs 列表中的设备后立即返回true .

如果您需要检查一个单元的所有设备是否与列表中的所有项目匹配,您可以使用:

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

请注意,如果您在selectedDeviceTypeIDs 中有重复项但在Unit 的Devices 中没有重复项,它仍然会返回true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多