我有一个像这样的分层类结构:
类别 - >模板 - >实例
一个类别包含多个模板,一个模板包含多个实例。
如果我通过所有3个表的连接查询数据库中的数据,则数据如下所示:
CategoryID | CategoryName | CategoryType | TemplateID | TemplateName | TemplateXYZ | InstanceID | InstanceName
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 1 | "InstA"
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 2 | "InstB"
1 | "CatA" | "TypeX" | 1 | "TempA" | "X" | 3 | "InstC"
1 | "CatA" | "TypeX" | 1 | "TempB" | "Y" | 4 | "InstD"
(只是一个例子,真正的数据表有更多的列)
在使用数据读取器循环使用此类数据时,C#中最好/最常用的方法是什么?
从头到尾我会这样做:
while(data.Read())
{
// Create new objects each time the ID changes and read the data from the first row
if(data["CategoryID"] != lastCategoryID) {
lastCategoryID = data["CategoryID"];
cat = new Category(data["CategoryName"], data["CategoryType"]);
catList.Add(cat);
}
if(data["TemplateID"] != lastTemplateID) {
lastTempateID = data["TemplateID"];
template = new Template(data["TemplateName"], data["TemplateXYZ"]));
cat.Templates.Add(template);
}
template.Instances.Add(new Instance(data["InstanceID"], data["InstanceName"]);
}
是否有更好,更优雅的解决方案来填充分层类对象?也许使用LINQ或Dictionaries?
注意:此问题与我关于best way to gather hierarchical data from a DB的其他问题有关。我把它分开了,因为这是两个不同的问题。
答案 0 :(得分:3)
你做什么似乎是一种很好的工作方式。只需确保对查询中的数据和ID列进行排序。按类别然后按模板排序。这样可以确保您不会返回其中一个ID并再次创建对象。
此外 - 如果模板可以分为多个类别,则必须将每个模板存储在某个位置的列表中,以确保您不会在类别上复制它们。
答案 1 :(得分:1)
当您从数据读取器中读取时,使用每行中的数据填充对象。此时不要担心重复:
var rawData = new List<Incoming>();
while (data.Read())
{
rawData.Add( new Incoming(data[0], data[1],data[2],data[3],data[4],data[5],data[6],data[7]));
}
,其中
public class Incoming
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int CategoryType { get; set; }
public int TemplateID { get; set; }
public string TemplateName { get; set; }
public int TemplateXYZ { get; set; }
public int InstanceID { get; set; }
public string InstanceName { get; set; }
public Incoming(int categoryID , string categoryName , int categoryType , int templateId,string templateName ,int templateXYZ , int instanceID , string instanceName )
{
CategoryID =categoryID;
CategoryName = categoryName; CategoryType = categoryType; TemplateID = templateId;
TemplateName = templateName; TemplateXYZ = templateXYZ; InstanceID = instanceID; InstanceName = instanceName;
}
}
然后您可以使用LINQ来获取层次结构的各个级别:
var categories = rawData.GroupBy (d => d.CategoryID );
答案 2 :(得分:-1)
以下内容将为您提供直接的课程方法:
string[] allLines = File.ReadAllLines("datafile.dat");
var query = from line in allLines
let data = line.Split('|')
select Category
{
CategoryID = data[0],
CategoryName = data[1],
CategoryType = data[2],
Template = new Template { TemplateID = data[3],
TemplateXYZ = data[4],
Instance = new Instance { InstanceID = data[5],
InstanceName = data[6] }
}
};