DataTable转化为List
public List<T> ConvertToList<T>(DataTable dt) where T : new()
{
// 定义集合
List<T> ts = new List<T>();
// 获得此模型的类型
Type type = typeof(T);
string tempName = "";
// 获得此模型的公共属性
PropertyInfo[] propertys = type.GetProperties();
T t = new T();
foreach (DataRow dr in dt.Rows)
{
t = new T();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;
// 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
if (dr[tempName] != DBNull.Value)
pi.SetValue(t, dr[tempName], null);
}
}
ts.Add(t);
}
return ts;
}
调用时:
ConvertToList<TreeNodeInt>(ds.Tables[0])
另附上 生成树形结构的简便方法,此处没有使用递归是他的高明之处,可以借鉴。
public class TreeNodeInt
{
public int id { get; set; }
public int? parentId { get; set; }
public string title { get; set; }
public string key { get; set; }
public string longLabel { get; set; }
public bool isFolder { get; set; }
public bool isLazy { get; set; }
public bool expand { get; set; }
//public bool Select { get; set; }
public bool unselectable { get; set; }
public bool hideCheckbox { get; set; }
public int treeLevel { get; set; }
public object obj { get; set; }
public List<TreeNodeInt> children { get; set; }
public static List<TreeNodeInt> ConvertToTree(List<TreeNodeInt> itemList)
{
itemList = itemList.OrderBy(p => p.title).ToList();
var tree = (from i in itemList
where i.parentId == null || i.parentId == 0
//orderby i.title
select new TreeNodeInt
{
id = i.id,
key = i.key,
//key = i.id.ToString(),
title = i.title,
longLabel = i.longLabel,
isFolder = i.isFolder,
expand = i.expand,
isLazy = i.isLazy,
//Select = i.Select,
unselectable = i.unselectable,
hideCheckbox = i.hideCheckbox,
treeLevel = i.treeLevel,
obj = i.obj
}).ToList();
Queue<TreeNodeInt> queue = new Queue<TreeNodeInt>(tree);
while (queue.Count > 0)
{
var node = queue.Dequeue();
var children = (from i in itemList
where i.parentId == node.id && i.id != node.id
//let idStr = SqlFunctions.StringConvert((double)i.id).Trim()
select new TreeNodeInt
{
id = i.id,
parentId = i.parentId,
key = i.key,
//key = i.id.ToString(),
title = i.title,
longLabel = i.longLabel,
isFolder = i.isFolder,
expand = i.expand,
isLazy = i.isLazy,
//Select = i.Select,
unselectable = i.unselectable,
hideCheckbox = i.hideCheckbox,
treeLevel = i.treeLevel,
obj = i.obj
}).ToList();
if (children.Count > 0)
{
node.children = children;
foreach (var child in children)
{
queue.Enqueue(child);
}
}
}
return tree;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)