0
点赞
收藏
分享

微信扫一扫

C# 将数据库中01,0101 ,0102。。形成Tree


1

01

True


0101

True


0102

True

4

0103

True

5

010101

True

6

010102

True

7

01010101

True

8

01010102

True

9

01010103

True

现将数据List  toDatatable

方法:

public static DataTable ToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}在把DataTable 转成排好序的集合
public static List<Data> CreatTree(DataTable dt)
{


var list = (from x
in dt.Rows.Cast<DataRow>()
group x by x["Code"].ToString().Length into g
select new { Key = g.Key, Items = g.ToList() }).OrderBy(x => x.Key);
List<Data> DataRoot = new List<Data>();
list.ToList()
.ForEach(x =>
{
if (x.Key == 2)
{
x.Items.ForEach(y => DataRoot.Add(new Data()
{
ID = y["Code"].ToString(),
EID = y["Id"].ToString(),
Name = y["Name"].ToString(),
Level = x.Key / 2 - 1
}));
}
else
{
x.Items.ForEach(y =>
{
Data data = null;
foreach (var item in DataRoot)
{
data = item[y["Code"].ToString().Substring(0, y["Code"].ToString().Length - 2)];
if (data != null) break;
}
if (data != null)
{
data.Childs.Add(new Data()
{
ID = y["Code"].ToString(),
EID = y["Id"].ToString(),
Name = y["Name"].ToString(),
Level = x.Key / 2 - 1
});
}
});
}
});
return DataRoot;
}model:
public class Data
public int Level { get; set; }
public string ID { get; set; }
public string EID { get; set; }
public string Name { get; set; }
public List<Data> Childs { get; set; } public Data() { Childs = new List<Data>(); }


public Data this[string id]
{
get
{
if (ID == id) return this;
Data data = null;
if (Childs.Count > 0)
{
data = Childs.Where(x => x.ID == id).SingleOrDefault();
if (data == null)
{
foreach (var item in Childs)
{
data = item[id];
if (data != null) break;
}
}
}
return data;
}
}

举报

相关推荐

0 条评论