Randy Hall
Randy Hall

Reputation: 8127

Linq query to select any in list against a list

Using EF Core code-first, and I want to find any record with a similar list of a foreign entities to the entity I already have.

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

Basically, "Select all the ClownModels where they have any Cars.Id that are in my MyClown.Cars"

Upvotes: 0

Views: 1272

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

Assuming that ClownModel has unique CarModel Id's, you can use the following query:

Matches All Ids

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;

Matches Any Ids

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;

Upvotes: 1

Related Questions