C# linq left join 操作表和datatable
https://blog.csdn.net/The_flying_pig/article/details/79568072
操作表:
现有sfcusn表,sfcmo表,为保证sfcusn表数据的完整使用left join 查询。结构如下
sql语句
---oracle写法SELECT A.usn,A.mo,A.upn,A.stage,B.line FROM sfcusn A,sfcmo B WHERE A.mo = B.mo(+)
linq语句
var query= from A in db.sfcusnjoin B in db.sfcmo on A.mo equals B.mo into tempfrom t in temp.DefaultIfEmpty()select new{ usn = A.usn, mo = A.mo, upn = A.upn, stage = A.stage, line = t==null?"":t.line //判断第二集合中可能为空};
操作datatable:
现需对两个datatable进行left join查询,结构如下
这里需要用到A,B中三个栏位。
如果是查询表用sql写当然是很简单了,可以仿看上面的sql写出来。
linq在操作datatable,注意字段的类型。
var query = from aa in A.AsEnumerable() join bb in B.AsEnumerable() on new { USERID = aa.Field<string>("USERID"), TRNDATE = aa.Field<string>("TRNDATE"), MODEC = aa.Field<string>("MODEC") } equals new { USERID = bb.Field<string>("USERID"), TRNDATE = bb.Field<string>("TRNDATE"), MODEC = bb.Field<string>("MODEC") } into temp from tt in temp.DefaultIfEmpty() select new { USERID = aa.Field<string>("USERID"), TOTAL = tt == null ? 0 : tt.Field<decimal>("TOTAL"), ECOUNT = aa.Field<decimal>("ECOUNT") == null ? 0 : aa.Field<decimal>("ECOUNT"), RATE = (100 * (tt == null ? 1 : (tt.Field<decimal>("TOTAL") == 0 ? 1 : aa.Field<decimal>("ECOUNT") / tt.Field<decimal>("TOTAL")))).ToString("#0.00") + "%", TRNDATE = a.Field<string>("TRNDATE") == null ? "" : a.Field<string>("TRNDATE"), MODEC = aa.Field<string>("MODEC") == null ? "" : aa.Field<string>("MODEC") };最后希望对大家有帮助谢谢!