C # LINQ to Entities query to intersect two different properties

I have 3 models named:

Pencil having Pencil.Id (int) and Pencil.Colors (IEnumerable) Property

A pen that has the Pen.Id (int) and Pen.Colors (IEnumerable) property

Colors with identifier and name.

Pencil is related to colors (many-to-many) Pen is related to colors (many-to-many)

I want to create a query that will show me the same colored pencils for a pen as I do.

I am using the following LINQ to-Entities query:

int id = id_of_the_pen_that_i_am_holding;
Pen p = db.Pens.Find(id);
var list = from m in db.Pencils where m.Colors.Intersect(p.Colors) != null select m;

IEnumerable, . ; 15 , 25 . , , , .

, int string, .

? .

: : # LINQ to Entities -

+5
2
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));
+6

, , , ( ), LINQ , :

IList<Pencil> sameColorPencils = new List<Pencil>();

Pen p = db.Pens.Find(id);

foreach (Color color in p.Color)
{
    var pencils = from pencil in db.Pencils
                  where pencil.Color == color
                  select pencil;

    foreach (Pencil pencil in pencils)
    {
        if (sameColorPencils.Count(e => e.Id == pencil.Id) == 0)
        {
            sameColorPencils.Add(pencils);
        }
    }
}
0

All Articles