linq to datatTable过滤条件
两个table
A
id name
1 aa
2 b
3 c
4 d
B
id name
1 a
2 b
DataTable dt_Except = a.Clone();
var query_Except = a.AsEnumerable().Except(b.AsEnumerable(), DataRowComparer.Default);
query_Except.ToList().ForEach(q => dt_Except.Rows.Add(q.ItemArray));
1:如果ID已存在则更新
2:如果ID不存在则添加
我想请问下上面2个条件怎么判断
void Main()
{
var A=new DataTable();
A.Columns.Add("id",typeof(int));
A.Columns.Add("name",typeof(string));
A.Rows.Add(1,"aa");
A.Rows.Add(2,"b");
A.Rows.Add(3,"c");
A.Rows.Add(4,"d");
var B=A.Clone();
B.Rows.Add(1,"a");
B.Rows.Add(2,"b");
B.Rows.Add(5,"f");
var query_Except =B.AsEnumerable().Except(A.AsEnumerable(), new MyCompare()).CopyToDataTable();
A.Merge(query_Except);
B=A;
}
public class MyCompare : IEqualityComparer<DataRow>
{
public bool Equals(DataRow t1, DataRow t2)
{
return (t1.Field<int>("id") == t2.Field<int>("id"));
}
public int GetHashCode(DataRow t)
{
return t.ToString().GetHashCode();
}
}