从多个数据集中填充类对象

时间:2015-01-14 04:47:18

标签: c# .net linq datatable

我想用 OrganismDT AntibioticDT 中的数据填充生物类对象。下面是Datatable结构,Class结构和我正在尝试的填充技术。基于 OrganismAliasId ,我必须填写AntibioticsDT [抗生素对象列表]行并分配给相应的生物对象。任何人都可以帮助我实现这个目标..

数据表

DataTable OrganismDT = new DataTable("Organism");
OrganismDT.Columns.Add("OrganismAliasId");
OrganismDT.Columns.Add("Name");

DataTable AntibioticsDT = new DataTable("Antibiotics");
AntibioticsDT.Columns.Add("OrganismAliasId");
AntibioticsDT.Columns.Add("Name");
AntibioticsDT.Columns.Add("Susceptibility");

班级结构:

public class Organism
{
 public int AliasId { get; set; }
 public string Name { get; set; }
 public List<Antibiotic> Antibiotics;
}


public class Antibiotic
{
 public string Name { get; set; }
 public string Susceptibility { get; set; }
}

将Datatable表填充到Class对象

List<Organism> Organisms = Organism.AsEnumerable().Select(row =>
new Organism
{
 AliasId = row.Field<int>("OrganismAliasId"),
 Name = row.Field<string>("Name"),
 Antibiotics = new List<Antibiotic>()
}).ToList();

1 个答案:

答案 0 :(得分:0)

这应该有效: -

List<Organism> Organisms = OrganismDT.AsEnumerable().Select(row =>
          new Organism
          {
            AliasId = row.Field<int>("OrganismAliasId"),
            Name = row.Field<string>("Name"),
            Antibiotics = AntibioticsDT.AsEnumerable()
                        .Where(x => x.Field<int>("OrganismAliasId") 
                                       == row.Field<int>("OrganismAliasId"))
                        .Select(x => new Antibiotic
                        {
                           Name = x.Field<string>("Name"),
                           Susceptibility = x.Field<string>("Susceptibility")
                        }).ToList()
            }).ToList();

此外,请注意您应该通过指定其数据类型来创建列,否则它可能会抛出运行时异常: -

AntibioticsDT.Columns.Add("OrganismAliasId",typeof(int));