Linq 查询列表中的 select any in list

Linq query to select any in list against a list

首先使用 EF Core 代码,并且我想查找具有与我已有的实体相似的外国实体列表的任何记录。

public class ClownModel {
    public int Id { get; set; }
    public List<CarModel> Cars { get; set; }
}
public class CarModel {
    public int Id { get; set; }
}

var MyClown = new ClownModel() { /*add properties*/ } 
//or maybe an existing record selected from database, just some ClownModel instance

基本上,“Select 所有 ClownModels 在我的 MyClown.Cars 中有任何 Cars.Id”

假设 ClownModel 具有唯一的 CarModel Id,您可以使用以下查询:

匹配所有 ID

var ids = MyClown.Cars.Select(c => c.Id).ToList();

var query = 
    from cm in ctx.ClownModel
    where cm.Cars.Where(c => ids.Contains(c.Id)).Count() == ids.Count
    select cm;

匹配任何 ID

var ids = MyClown.Cars.Select(c => c.Id).ToList();

var query = 
    from cm in ctx.ClownModel
    where cm.Cars.Where(c => ids.Contains(c.Id)).Any()
    select cm;