using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; namespace Hncore.Infrastructure.Common { public static class ListHelper { #region 字符串转化为泛型集合 /// /// 字符串转化为泛型集合 /// /// 字符串 /// 要分割的字符 /// public static List StrToList(string str, char splitstr) { List list = new List(); if (string.IsNullOrEmpty(str)) { return list; } if (!str.Contains(splitstr)) { list.Add((T)Convert.ChangeType(str, typeof(T))); return list; } else { string[] strarray = str.Split(splitstr); foreach (string s in strarray) { if (s != "") list.Add((T)Convert.ChangeType(s, typeof(T))); } return list; } } /// /// 字符串转化为泛型集合 /// /// 字符串 /// public static List StrToList(string str) { return StrToList(str, ','); } #endregion public static string ListToStr(List list, string splitstr=",") { string str = ""; list.ForEach(t => { str += t + splitstr; }); if (str.EndsWith(splitstr)) { str = str.Substring(0, str.Length - splitstr.Length); } return str; } #region 转换几个中所有元素的类型 /// /// 转换几个中所有元素的类型 /// /// /// /// public static List ConvertListType(List list) { if (list == null) { return null; } List newlist = new List(); foreach (T t in list) { object to = new object(); if (typeof(To).Name == "Guid") { to = Guid.Parse(t.ToString()); } else { to = Convert.ChangeType(t, typeof(To)); } newlist.Add((To)to); } return newlist; } #endregion #region 转化一个DataTable /// /// 转化一个DataTable /// /// /// /// public static DataTable ToDataTable(IEnumerable list) { //创建属性的集合 List pList = new List(); //获得反射的入口 Type type = typeof(T); DataTable dt = new DataTable(); //把所有的public属性加入到集合 并添加DataTable的列 Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in list) { //创建一个DataRow实例 DataRow row = dt.NewRow(); //给row 赋值 pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); //加入到DataTable dt.Rows.Add(row); } return dt; } #endregion } }