- 将DataTable 转换List <T>
1)要求DataTable中的列名称必须和实体的属性名称相同
public static List<TResult> DataTableToList<TResult>(DataTable dt) where TResult : class,new() { //创建一个属性的列表 List<PropertyInfo> prlist = new List<PropertyInfo>(); //获取TResult的类型实例 反射的入口 Type t = typeof(TResult); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); }); //创建返回的集合 List<TResult> oblist = new List<TResult>(); foreach (DataRow row in dt.Rows) { //创建TResult的实例 TResult ob = new TResult(); //找到对应的数据 并赋值 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) { Type type = p.PropertyType; if (type.Name == "String") { t.GetProperty(p.Name).SetValue(ob, row[p.Name].ToString(), null); p.SetValue(ob, row[p.Name], null); } else { var value = Activator.CreateInstance(type); if (type.IsEnum) { string str = row[p.Name].ToString(); value = Enum.Parse(type, str, true); } else { value = Convert.ChangeType(row[p.Name], type); } p.SetValue(ob, value, null); } } }); //放入到返回的集合中. oblist.Add(ob); } return oblist; }
2)要求实体的属性名称的顺序跟DataTable中的列名对应的顺序相同
public static List<TResult> DataTableToList<TResult>(DataTable dt) where TResult : class,new() { //创建一个属性的列表 List<string> columNamelist = new List<string>(); foreach (DataColumn dc in dt.Columns) { if (!columNamelist.Contains(dc.ColumnName)) columNamelist.Add(dc.ColumnName); } //创建一个属性的列表 List<PropertyInfo> prlist = new List<PropertyInfo>(); //获取TResult的类型实例 反射的入口 Type t = typeof(TResult); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach<PropertyInfo>(t.GetProperties(), p => { prlist.Add(p); }); //创建返回的集合 //创建返回的集合 List<TResult> oblist = new List<TResult>(); foreach (DataRow row in dt.Rows) { //创建TResult的实例 TResult ob = new TResult(); //找到对应的数据 并赋值 for (int i = 0; i < columNamelist.Count; i++) { string columName = columNamelist[i]; if (row[columName] != DBNull.Value) { PropertyInfo p = prlist[i]; Type type = p.PropertyType; if (type.Name == "String") { t.GetProperty(p.Name).SetValue(ob, row[columName].ToString(), null); } else { var value = Activator.CreateInstance(type); if (type.IsEnum) { string str = row[columName].ToString(); value = Enum.Parse(type, str, true); } else { value = Convert.ChangeType(row[columName], type); } t.GetProperty(p.Name).SetValue(ob, value, null); } } } //放入到返回的集合中. oblist.Add(ob); } return oblist; }
2.将IEnumerable接口对象转换成DataTable
public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value) where TResult : class { //创建属性的集合 List<PropertyInfo> pList = new List<PropertyInfo>(); //获得反射的入口 Type type = typeof(TResult); DataTable dt = new DataTable(); //把所有的public属性加入到集合 并添加DataTable的列 Array.ForEach<PropertyInfo>( type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in value) { //创建一个DataRow实例 DataRow row = dt.NewRow(); //给row 赋值 pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); //加入到DataTable dt.Rows.Add(row); } return dt; }
3.对象的克隆
1)通过序列化与反序列化得到一个对象的克隆(注意该对象必须声明为可序列化,而且他的所有属性的类型都是可序列化的)
public static object Clone(object obj) { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, obj); memoryStream.Position = 0; return formatter.Deserialize(memoryStream); }
2)通过实现ICloneable接口实现克隆
public class T : ICloneable { public object Clone() { //如果实体中含有引用类型,则需要对每个引用类型进行深度拷贝 return this.MemberwiseClone(); //这里可以通过Object中的方法实现浅拷贝 } }
4.常用的一些LINQ
1)把DataTable转换成Dictionary、Array、List等等
var dic = (from row in dt.AsEnumerable()
select (new { PowerRoomID = row["PowerRoomID"].ToString(), PowerRoomName = row["PowerRoomName"].ToString() })
).Distinct().ToDictionary(k => k.PowerRoomName, v => v.PowerRoomID); dic = dt.AsEnumerable().Select(row => new { PowerRoomID = row["PowerRoomID"].ToString(), PowerRoomName = row["PowerRoomName"].ToString() }).Distinct().ToDictionary(k => k.PowerRoomName, v => v.PowerRoomID);
2.过滤数据源并且可以创建临时实体类型的数据源
1)生成局部的临时实体类型的数据源(这里的局部是指下面的source是局部,不能生成全局变量)
var source = (from row in devModel.Source where row.Type =="类型" && row.IsChecked == true select new { DevNo = row.DevNo, DevName = row.DevName }).ToList();source = devModel.Source.Where(row => row.Type == "类型" && row.IsChecked == true).Select(row => new { DevNo = row.DevNo, DevName = row.DevName }).ToList();
2)全局的临时实体类型数据源
List<Tuple<int,string>> source = (from row in devModel.Source where row.Type == "类型" && row.IsChecked == true select new Tuple<int, string>(row.Id, row.DevName)).ToList();source = devModel.Source.Where(row => row.Type == "类型" && row.IsChecked == true).Select(row => new Tuple<int, string>(row.Id, row.DevName)).ToList();
3 序列化与反序列化操作
将对象序列化成字符串


将对象序列化成字符串 public static string Serialize<T>(T obj) { if (obj == null) { return null; } string ret = ""; using (MemoryStream stream = new MemoryStream()) { DataContractSerializer serializer = new DataContractSerializer(obj.GetType()); using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8)) { serializer.WriteObject(binaryDictionaryWriter, obj); binaryDictionaryWriter.Flush(); } ret = Encoding.UTF8.GetString(stream.ToArray()); } return ret; }
将对象序列化成配置xml文件 (保存)


public static void DataContractSerializeToFile<T>(T t, string fileName) { if (t == null) { return; } using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.Default }; using (XmlWriter xmlWriter = XmlWriter.Create(fileStream, xmlWriterSettings)) { DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T)); dataContractSerializer.WriteObject(xmlWriter, t); xmlWriter.Flush(); } } } public static void XmlSerializeToFile<T>(T t, string fileName) { if (t == null) { return; } using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Indent = true, Encoding = Encoding.Default }; using (XmlWriter xmlWriter = XmlWriter.Create(fileStream, xmlWriterSettings)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); xmlSerializer.Serialize(xmlWriter, t); xmlWriter.Flush(); } } }
将字符串反序列化为对象


public static T DataContractDeserialize<T>(string xml) { T ret = default(T); if (string.IsNullOrEmpty(xml)) { return ret; } using (MemoryStream stream = new MemoryStream()) { byte[] bytes = Encoding.UTF8.GetBytes(xml); stream.Write(bytes, 0, bytes.Length); stream.Position = 0L; DataContractSerializer serializer = new DataContractSerializer(typeof(T)); using (XmlDictionaryReader binaryDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)) { ret = (T)serializer.ReadObject(binaryDictionaryReader); } } return ret; }
将xml配置文件反序列化为对象(实体初始化)


public static T DataContractDeserializeByFile<T>(string fileName) { T result = default(T); if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName)) { return result; } using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T)); using (XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(fileStream, XmlDictionaryReaderQuotas.Max)) { result = (T)dataContractSerializer.ReadObject(xmlDictionaryReader); } } return result; } public static T XmlDeserializeByFile<T>(string fileName) { T result = default(T); if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName)) { return result; } using (FileStream fileStream = new FileStream(fileName, FileMode.Open)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); result = (T)xmlSerializer.Deserialize(fileStream); } return result; }
总结:以上纯属个人的理解,对于有些地方觉得还是理解不是很深,有不足之处和错误的地方希望大家帮我指出。谢谢