简体   繁体   English

在Linq中将两个数据表作为父子表连接

[英]Joining two datatables as parent-child in linq

I need to build a typed list of parent-child objects that are read from two different Excel sources: One describes parent object, another describes child objects. 我需要构建从两个不同的Excel来源读取的父子对象的类型列表:一个描述父对象,另一个描述子对象。 The hierarchy is only 2 layers ever. 层次结构只有2层。
Reading into excel is not the issue, as it is read into 2 untyped datatables, but joining the information is. 读入excel并不是问题,因为它被读入2个未类型化的数据表中,但加入信息却成为问题。

The structure is very plain: 结构非常简单:
Parent has an ID and some text fields Children have a parentID (so its 1-m) and some text fields 父级有一个ID和一些文本字段子级有一个parentID(因此是1-m)和一些文本字段

The objects that these are to be populated into looks like this: 这些将要填充的对象如下所示:

public class ParkingSites
{
    public List<ParkingLot> Lots { get; set; }

    public ParkingSites(List<ParkingLot> arg)
    {
        Lots = arg;
    }
}

public class ParkingLot
{
    public List<Bay> Bays{ get; set; }
    public int Id { get; set; }
    public List<string> ParkingLotDetails { get; set; } 
    public ParkingLot()
    {

    }
}

public class Bay
{
    public List<string> BayDetails { get; set; }
    public int ParentId { get; set; }    
    public Bay()
    {

    }
}

The excel sources have a fixed column order with the parent sheet's first column being the parentId, and the first column on the child sheet also being the parentId. excel源代码具有固定的列顺序,其中父表的第一列为parentId,子表的第一列也为parentId。

EDIT: After playing around a bit, I just made both parent and child classes typed, as the initial reason for leaving them mostly untyped lead to more problems than it prevented. 编辑:经过一番尝试后,我只是使父类和子类都被键入了,因为最初使它们大部分都没有类型的原因导致了比它所能防止的更多的问题。 This is part of a larger project where the untypedness is a better solution for our problem on the other classes with data that is not hierarchial. 这是一个较大项目的一部分,在该项目中,无类型性是对其他非分层数据类的问题的更好解决方案。

You can simply group the list of children by the parent id, and then iterate over the parents and add each child that belongs to it. 您可以简单地按父ID将子列表分组,然后遍历父并添加属于它的每个子。

For example, you could use ToLookup : 例如,您可以使用ToLookup

// assuming you have all Bay instances in a collection called bays
var baymap = bays.ToLookup(b => b.ParentId);

// and all ParkingLot instances in a collection called lots
foreach(var lot in lots)
    lot.Bays.AddRange(baymap[lot.Id]);

or, using the first element in the details lists: 或者,使用详细信息列表中的第一个元素:

var baymap = bays.ToLookup(b => b.BayDetails[0]);

foreach(var lot in lots)
    lot.Bays.AddRange(baymap[lot.ParkingLotDetails[0]]);

or, using Where without a lookup (probably slower, depends on your data): 或者,用Where没有查找(可能比较慢,取决于数据):

foreach(var lot in lots)
    lot.Bays.AddRange(bays.Where(b => b.ParentId == lot.Id));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM