【问题标题】:Unable to check if a list of int is completely contained in another int list无法检查一个 int 列表是否完全包含在另一个 int 列表中
【发布时间】:2021-05-15 08:06:20
【问题描述】:

我有一个表示服务 ID 的 int 列表。我想确保所有这些 id 都存在于数据库中。 换句话说,我想扫描 id 列表和服务表,以确保所有这些 id 都存在于数据库中。

我试过这个:

List<int> ids;//[1,52]
var x = _context.Services.Any(s => ids.Contains(s.Id));//service ids = [1,2,3]

但它返回了 True ,这不是所需的输出。

我也试过这样:

_context.Services.Any(s => ids.Any(id => id == s.Id)!=null);

这样

_context.Services.Any(s => ids.Any(id => id == s.Id)!=null);

也没有运气。什么是正确的方法?我正在使用 EFCore 3.1.8

【问题讨论】:

    标签: linq .net-core ef-core-3.1


    【解决方案1】:

    通常你会使用 Queryable.Except。

    如果您有两个项目序列,并且除了 B 之外执行 A,那么如果您什么都没有,那么显然 A 中的每个项目也是 B 中的项目。

    IEnumerable<int> requiredIds = ...
    IQueryable<int> serviceIds = dbContext.Services.Select(service => service.Id);
    
    bool someRequiredIdsMissing = requiredIds.Except(serviceIds).Any();
    

    唉,您的 A 是本地的,而您的 B 在数据库中。所以我想这行不通。

    您可以做的是仅保留所需 ID 列表中的服务 ID,并计算它们。如果更少,那么显然一些 requiredIds 不在 serviceIds 中。

    var requiredServiceIds = serviceIds.Where(serviceId => requiredIds.Contains(serviceId);
    
    bool allRequiredAvailale = requiredServiceIds.Count() != requiredIds.Count();
    

    例子:

    IEnumerable<int> requiredIds = new [] {1, 2, 7, 20};
    Total: 4 elements
    
    Your service Ids are: 1 2 4 5 8 20 25
    
    requiredServiceIds : 1 2 20: total 3 elements
    So allRequiredAvailale is false;
    

    示例 2:

    Your service Ids are: 1 2 4 5 7 8 20 25
    requiredServiceIds : 1 2 7 20: total 4 elements
    So allRequiredAvailale is true;
    

    【讨论】:

    • 如果不能保证 id 的唯一性则不起作用
    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 2015-07-01
    相关资源
    最近更新 更多