我试图在.NET 2.0(没错,2.0)的应用程序来填充分层数据而现在升级为假表(所以没有LINQ,LINQ桥,或其他东西)。有没有更好的方法来将SQL中的分层数据填充到类结构,C#或VB.NET中?
我不知道是否有更好的方法来填充分层数据到这个阶层结构?我很确定有一个更好的方法来完成这个任务。
这将是非常高兴看到一个好办法做到这一点。如果任何人有时间展示.NET 2.0的方式,并且如果有其他方式,他们会在.NET 4.0+中做到这一点,那将非常棒。
这里是节点类型结构的一个例子:
using System.Collections.Generic;
public class ExampleNode
{
private int _id;
private Nullable<int> _parentId;
private int _depth;
private List<ExampleNode> _children = new List<ExampleNode>();
public ExampleNode()
{
}
public virtual int ApplicationNumber {
get { return _id; }
set { _id = value; }
}
public virtual Nullable<int> ParentId {
get { return _parentId; }
set { _parentId = value; }
}
public virtual int Depth {
get { return _depth; }
set { _depth = value; }
}
public virtual List<ExampleNode> Children {
get { return _children; }
set { _children = value; }
}
}
这里是正被使用来填充所述节点结构的一例的功能。看来这不是实现这一目标的最佳方式,它有可能不会填充孙子类型数据。 Depth从存储过程中返回,作为层级中的级别(0级别的项目是顶级,如果某个节点是顶级节点的子级,则它位于级别1,顶级节点的孙级是级别2等)
public List<ExampleNode> GetNodes()
{
// This may not be optimal.
List<ExampleNode> nodeList = new List<ExampleNode>();
Dictionary<int, ExampleNode> nodeDictionary = new Dictionary<int, ExampleNode>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(ConfigurationManager.ConnectionStrings("SqlServer").ConnectionString, CommandType.StoredProcedure, "proc_GetNodeStructure", new SqlParameter("@UserId", userId), new SqlParameter("@NodeTypeId", nodeType))) {
while (reader.Read) {
ExampleNode nodeInstance = new ExampleNode();
nodeInstance.Id = Convert.ToInt32(reader("Id"));
nodeInstance.Depth = Convert.ToInt32(reader("Depth"));
if (!Information.IsDBNull(reader("ParentId"))) {
nodeInstance.ParentId = Convert.ToInt64(reader("ParentId"));
}
// Add to list
nodeList.Add(nodeInstance);
// Add to dictionary
nodeDictionary.Add(nodeInstance.Id, nodeInstance);
}
}
foreach (ExampleNode item in nodeList) {
if (item.ParentId.HasValue) {
nodeDictionary(item.ParentId).Children.Add(item);
}
}
for (int i = nodeList.Count - 1; i >= 0; i += -1) {
if (nodeList(i).Depth > 0) {
nodeList.RemoveAt(i);
}
}
return nodeList;
}
我不知道很多人会考虑转向LINQ进行“升级”。 – 2012-07-09 02:12:19
您是否必须使用数据读取器?我在想,如果你可以使用数据表并在递归函数中使用它,首先获得根节点('ParentId IS NULL'),然后根据父id值('ParentId = ')等等。使用'LINQ'你有更多的灵活性,但是如果你被限制使用'.NET 2.0',你就不能使用它。 –
2012-07-09 02:12:29