c# - Linq Join: Join using a mapping table and associate objects -
i trying write linq query make basic join. have 2 arrays
park[] parks = new park[]{ new park() {id = 1, name = "free park"}, new park() {id = 2, name = "cost park"}, new park() {id = 3, name="sneak in park"} };
and
facility[] facilities = new facility[] { new facility() { id = 1, name = "swing", minimumage = 1, maximumage = 120}, new facility() { id = 2, name = "slide", minimumage = 1, maximumage = 200}, new facility() { id = 3, name = "see-saw", minimumage = 1, maximumage = 300} };
each park can have 0...n
facilities, hence have set of mapping objects
parkfacility[] associations = new parkfacility[] { new parkfacility() {parkid = 1, facilityid = 1}, new parkfacility() {parkid = 1, facilityid = 2}, new parkfacility() {parkid = 1, facilityid = 3}, new parkfacility() {parkid = 2, facilityid = 1}, new parkfacility() {parkid = 3, facilityid = 2} };
this definition of class park
class park { public int id { get; set; } public string name { get; set; } public facility[] facilities { get; set; } }
is possible use joins , associate appropriate facilities parks? i.e. set facilities
array in park appropriately mapped using associations
?
edit: research far..
var x_temp = g in parks join j in associations on g.id equals j.parkid h select new park() { name = g.name, id = g.id, facilities = (from u in h join m in facilities on u.facilityid equals m.id select m).toarray() };
i tried using sub-linq query , works, looking solution only joins
you can create lookup park id facilities, , use populate facilities
property on each of park
objects. note best place in constructor of park
, in keeping existing code snippet in object initializer:
var lookup = associations.tolookup(pf => pf.parkid, pf => facilities.single(f => f.id == pf.facilityid)); park[] parks = new park[]{ new park() {id = 1, name = "free park", facilities = lookup[1].toarray()}, new park() {id = 2, name = "cost park", facilities = lookup[2].toarray()}, new park() {id = 3, name="sneak in park", facilities = lookup[3].toarray()} };
additionally, helpful store facility
, park
instances in dictionary
mapping id instance. in case lookup wouldn't need linear scan through facilities each association.
Comments
Post a Comment