C # LINQ to Entities - properties at the intersection of an object and a set of objects

I asked a similar question, which was trying to understand how to get models in another set that have the same property with what I am holding.

Now the problem is this: So, as the "similar property" was called, which actually directed me to another set.

Original post: C # LINQ to Entities query to intersect two different properties

I have 3 models named:

  • Pencil having the Pencil.Id (int) and Pencil.Colors (IEnumerable) property
  • A pen with the Pen.Id (int) and Pen.Colors (IEnumerable) property
  • Colors with identifier and name.

The color model is IEnumerable, so it has more than one color. For instance; the pen has 15 different colors, and the pencil has 25 different colors. I want to bring an appropriate pencil if one of the colors of the pen that I am holding is also available in the color palette of this pencil.

Raphael is a great solution https://stackoverflow.com/a/4646263

int id = id_of_the_pen_that_i_am_holding;
Pen p = db.Pens.Find(id);
var penColorIds = p.Color.Select(m => m.Id).ToList();
var list = db.Pencils.Where(pencil => pencil.Color.Any(color => penColorIds.Contains(color.Id));

So, everything is in order and works like a charm, but what about learning the names of common colors? We get other properties that have the same color, but what color is it?

I would appreciate it if someone could produce this LINQ query. I am new to LINQ and really appreciate any help.

+3
source share
3 answers

If you hold several pens in your hand, use (in a variable pens)

var colors = pens.SelectMany(p=>p.Colors).Distinct(); 
var commonColors = db.Pencils.SelectMany (p => p.Colors.Where(c=>colors.Contains(c))).Distinct()

, ( pen)

var colors = pen.Colors;
var commonColors = db.Pencils.SelectMany (p => p.Colors.Where(c=>colors.Contains(c))).Distinct()
+1

Intersect , SelectMany.

var commonColors = 
    db.Pens.SelectMany(p => p.Colors)
        .Insersect(db.Pencils.SelectMany(hb => hb.Colors));

Intersct, , , ( ), ,

var commonColors = 
    db.Pens.SelectMany(p => p.Colors).Distinct()
        .Insersect(db.Pencils.SelcectMany(hb => hb.Colors).Distinct());

Pen do

Pen p = db.Pens.Find(id); 
var commonColors = Pen.Colors
    .Insersect(db.Pencils.SelcectMany(p => p.Colors));
+2

Well, I’m not sure that it makes sense to get everything in one request, but with this you should get a list of the anonymous pencil object and a list of common colors for each pencil (untested).

int id = id_of_the_pen_that_i_am_holding;
Pen p = db.Pens.Find(id);
var penColorIds = p.Color.Select(m => m.Id).ToList();

var list = db.Pencils.Where(pencil => pencil.Color.Any(color => penColorIds.Contains(color.Id))
.Select(l => new {
   pencil = l,
   colors = l.Color.Where(c => penColorIds.Contains(c.Id))
});
+1
source

All Articles