Harry Hathorn Harry Hathorn - 3 months ago 12
C# Question

Make an array with all the values from one array which match the value in another array in C#

I have a database class like this:

public partial class Colour
{
public int ColourID { get; set; }
public string Colour1 { get; set; }
}


Another class like this:

public partial class RangeColour
{
public int RangeColourID { get; set; }
public Nullable<int> RangeID { get; set; }
public Nullable<int> ColourID { get; set; }
}


and a third class like this:

public partial class Range
{
public int RangeID { get; set; }
public string RangeName { get; set; }
}


Each
Range
instance can have many colours from the
Colour
class. All the Ranges are and their colours are linked in the
RangeColour
class.

This relationship is established as follows:
RangeID
in the
Range
table is a primary key to
RangeID
in the
RangeColour
table.

In like manner
ColourID
in the
Colour
table is a primary key to
ColourID
in the
RangeColour
table.

I get an
IEnumerable
of a specific range in my c# method as follows:

public class HomeController : Controller

{
Entities db = new Entities();

public ActionResult Product(int id)
{

IEnumerable<RangeColour> colran = db.RangeColours.Where(c => c.RangeID == id);
//other code
}
}


Now that I have got an
IEnumerable
of the
RangeColours
table of all the
colourID
which belong to that
RangeID
how can I make a new
IEnumerable
which has all the
Colour1
that go with those
ColourID
's values from the
Colour
table in it to? I'm sure this can be accomplished with a lambda expression of some sort.

Answer

You can use Join extension on IQueryable to get the colors.

var colors = db.Colors.Join(db.RangeColours.Where(c => c.RangeID == item.RangeID), c => c.ColourID, r => r.ColourID, (c, r) => c);