一般递归都要每层去查库,这样不仅浪费了连接、断开、处理数据库的资源,而且极大的消耗了计算时间,有了Linq之后,直接分析数据集合的父子层级关系,不仅提高了速度,更是可以将处理的的过程抽象出来实现复用。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace program
{
/// <summary>
/// 将DataTable改为Tree
/// </summary>
class DataTableToTree
{
DataTable dt;
string parentField;
string refID;
string firstLever;
StringBuilder sb = new StringBuilder("<root>");
List<string> columnList = new List<string>();
/// <summary>
/// 初始化
/// </summary>
/// <param name="dt">数据表</param>
/// <param name="parentField">关联字段[父]</param>
/// <param name="refID">关联字段[子]</param>
/// <param name="firstLever">顶级目录的父级值</param>
public DataTableToTree(DataTable dt, string parentField, string refID,string firstLever="0")
{
this.dt = dt;
this.parentField = parentField;
this.refID = refID;
this.firstLever = firstLever;
fillColumn();
}
public XElement getXml()
{
if (dt.Rows.Count == 0 || parentField.Trim() == "" || refID.Trim() == "")
return null;
doLoop(firstLever);
return XElement.Parse(sb.Append("</root>").ToString());
}
private void doLoop(string parent)
{
var list = from r in dt.AsEnumerable()
where r[parentField].ToString() == parent
select r;
foreach (var r in list)
{
sb.Append(getXmlNode(r));
doLoop(r[refID].ToString());
sb.Append("</item>");
}
}
private string getXmlNode(DataRow r)
{
StringBuilder sb_=new StringBuilder("<item ");
foreach (string columnName in columnList)
sb_.Append(columnName + "='" + r[columnName].ToString() + "' ");
return sb_.Append(">").ToString();
}
private void fillColumn()
{
foreach (DataColumn c in dt.Columns)
columnList.Add(c.ColumnName);
}
}
}