139 lines
3.8 KiB
C#
139 lines
3.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
|
|
namespace Hncore.Infrastructure.Common
|
|
{
|
|
public static class ListHelper<T>
|
|
{
|
|
#region 字符串转化为泛型集合
|
|
|
|
/// <summary>
|
|
/// 字符串转化为泛型集合
|
|
/// </summary>
|
|
/// <param name="str">字符串</param>
|
|
/// <param name="splitstr">要分割的字符</param>
|
|
/// <returns></returns>
|
|
public static List<T> StrToList(string str, char splitstr)
|
|
{
|
|
List<T> list = new List<T>();
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 字符串转化为泛型集合
|
|
/// </summary>
|
|
/// <param name="str">字符串</param>
|
|
/// <returns></returns>
|
|
public static List<T> StrToList(string str)
|
|
{
|
|
return StrToList(str, ',');
|
|
}
|
|
|
|
#endregion
|
|
|
|
public static string ListToStr(List<T> 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 转换几个中所有元素的类型
|
|
|
|
/// <summary>
|
|
/// 转换几个中所有元素的类型
|
|
/// </summary>
|
|
/// <typeparam name="To"></typeparam>
|
|
/// <param name="list"></param>
|
|
/// <returns></returns>
|
|
public static List<To> ConvertListType<To>(List<T> list)
|
|
{
|
|
if (list == null)
|
|
{
|
|
return null;
|
|
}
|
|
List<To> newlist = new List<To>();
|
|
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
|
|
|
|
/// <summary>
|
|
/// 转化一个DataTable
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <param name="list"></param>
|
|
/// <returns></returns>
|
|
public static DataTable ToDataTable(IEnumerable<T> list)
|
|
{
|
|
//创建属性的集合
|
|
List<PropertyInfo> pList = new List<PropertyInfo>();
|
|
//获得反射的入口
|
|
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
|
|
|
|
}
|
|
}
|