您的位置:首页 > 其它

DataTable转化为List

2016-04-05 16:49 411 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: