如果你要进行多次对比的话,可以先将dt2扔到一个字典中,只需要循环一次,当然如果只是一次,那就没必要了,直接用linq最简单
static void Start() {
var dt1 = StructTable1();
var dt2 = StructTable2();
var dict = dt2.AsEnumerable().ToDictionary(dr => { return Convert.ToInt32(dr["ID"]); });
int id = Convert.ToInt32(dt1.Rows[0]["ID"]);
DataRow n = dict[id];
string name = n["Name"].ToString();
int age = Convert.ToInt32(n["Age"]);
}
static DataTable StructTable1() {
DataTable dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("ID", typeof(int)));
dt1.Columns.Add(new DataColumn("Name", typeof(string)));
DataRow dr1 = dt1.NewRow();
dr1["ID"] = 1;
dr1["Name"] = "45";
dt1.Rows.Add(dr1);
return dt1;
}
static DataTable StructTable2() {
DataTable dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("ID", typeof(int)));
dt2.Columns.Add(new DataColumn("Name", typeof(string)));
dt2.Columns.Add(new DataColumn("Age", typeof(string)));
DataRow dr1 = dt2.NewRow();
dr1["ID"] = 1;
dr1["Name"] = "45";
dr1["Age"] = 91;
DataRow dr2 = dt2.NewRow();
dr2["ID"] = 2;
dr2["Name"] = "456";
dr2["Age"] = 92;
dt2.Rows.Add(dr1);
dt2.Rows.Add(dr2);
return dt2;
}
1.listA.Where(t=>t.Value == listB.FirstOrDefault(g=>t.Id == g.Id).Value);//效率较低,尤其没索引
2.listA.Join(listB, t => t.Id, g => g.Id, (a, b) => new { a.Id, Bid = b.Id,b.N }).Where(t=>t.Id == t.Bid);//效率较高
others...
大致如上,实体和表操作自己替换。
嗯嗯 好的 大佬
我只这样写的
var datalist = from n in dt1.AsEnumerable()
from m in dt2.AsEnumerable()
where m.Field<string>("Name") == n.Field<string>("Name")
select new
{
ID = n["ID"].ToString(),
Name = n["Name"].ToString(),
Age = m["Age"].ToString()
};
Linq最简洁直接,Lambda好用到爆
ListB.Where(d=>ListA.Any(x=>x.ID==d.ID))