Linq Join:使用映射表和关联对象加入

时间:2015-04-01 16:54:07

标签: c# linq join

我正在尝试编写一个linq查询来进行非常基本的连接。我有两个数组

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"}
};

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}
};

每个公园都有0...n个设施,因此我们有一套映射对象

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}
};

这是类Park

的定义
class Park
{
        public int ID { get; set; }
        public String Name { get; set; }
        public Facility[] Facilities { get; set; }
}

是否可以仅使用连接并将适当的设施与公园相关联?即将Park中的Facilities数组设置为使用associations

进行适当映射的数组

编辑:到目前为止我的研究......

var x_temp = from g in parks
             join j in associations on g.ID equals j.ParkID into 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()
             };

我尝试使用sub-linq查询并且它有效,但我正在寻找一个加入的解决方案

1 个答案:

答案 0 :(得分:1)

您可以创建从park id到facility的查找,并使用它来填充每个Facilities对象上的Park属性。请注意,执行此操作的最佳位置是Park的构造函数,但为了与现有代码保持一致,此代码段将在对象初始值设定项中执行:

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()}
};

此外,将FacilityPark个实例存储在Dictionary中,将ID映射到实例会很有帮助。在这种情况下,您的查找不需要对每个关联的所有工具进行线性扫描。