将DataTable转换为List
例有以下两个DataTable:
DataTable table1 = new DataTable();
table1.Columns.Add("Name");
table1.Columns.Add("Age", Type.GetType("System.Int32"));
table1.Columns.Add("Gender");
DataRow row1 = table1.NewRow();
row1["Name"] = "张三";
row1["Age"] = 18;
row1["Gender"] = "男";
table1.Rows.Add(row1);
row1 = table1.NewRow();
row1["Name"] = "李四";
row1["Age"] = 17;
row1["Gender"] = "男";
table1.Rows.Add(row1);
DataTable table2 = new DataTable();
table2.Columns.Add("Name");
table2.Columns.Add("Age", Type.GetType("System.Int32"));
table2.Columns.Add("Gender");
DataRow row2 = table2.NewRow();
row2["Name"] = "张三";
row2["Age"] = 18;
row2["Gender"] = "男";
table2.Rows.Add(row2);
row2 = table2.NewRow();
row2["Name"] = "李四";
row2["Age"] = 18;
row2["Gender"] = "男";
table2.Rows.Add(row2);
转换辅助类
public class ConvertHelperwhere T : new()
{
public static IListConvertToModel(DataTable dt)
{
// 定义集合
IListts = new List ();
// 获得此模型的类型
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
将两个table转换为List集合
Listp1 = ConvertHelper .ConvertToModel(table1).ToList();
Listp2 = ConvertHelper .ConvertToModel(table2).ToList();
Persion类
public class Persion
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
查询差集
var result = p1.Where(a => !p2.Exists(b => b.Name == a.Name && b.Age == a.Age && b.Gender == a.Gender )).ToList();
两种方法解决这个问题
粗暴方法。table1作为对比表。循环table2表中每行数据,然后循环每列数据。得到后与table1中的数据进行对比
优雅一些的方法。针对DataRow定义对应的class。然后class实现ICompare这个接口,定义比较规则。最后,将table1转换成List