linq 的 left join 如何優化寫法.

chaojie_sea 2014-07-10 11:52:27
如:

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("matcode", typeof(System.String));
dt1.Columns.Add("matsize", typeof(System.Decimal));
dt1.Columns.Add("matsunit", typeof(System.String));
dt1.Columns.Add("matcolor", typeof(System.String));
dt1.Columns.Add("asn_sqty", typeof(System.Decimal));
//
dt2.Columns.Add("matcode", typeof(System.String));
dt2.Columns.Add("matsize", typeof(System.Decimal));
dt2.Columns.Add("matsunit", typeof(System.String));
dt2.Columns.Add("matcolor", typeof(System.String));
dt2.Columns.Add("asn_sqty", typeof(System.Decimal));
//
var res1 = from r1 in dt1.AsEnumerable()
join r2 in dt2.AsEnumerable() on new
{
matcode = r1.Field<string>("matcode").Trim(),
matsize = r1.Field<decimal>("matsize"),
matsunit = r1.Field<string>("matsunit").Trim(),
matcolor = r1.Field<string>("matcolor").Trim(),
} equals new
{
matcode = r2.Field<string>("matcode").Trim(),
matsize = r2.Field<decimal>("matsize"),
matsunit = r2.Field<string>("matsunit").Trim(),
matcolor = r2.Field<string>("matcolor").Trim(),
} into g1
from r2 in g1.DefaultIfEmpty()
where r1.Field<decimal>("asn_sqty") != (r2 == null ? 0 : r2.Field<decimal>("asn_sqty"))
select new
{
matcode = r1.Field<string>("matcode").Trim(),
matsize = r1.Field<decimal>("matsize"),
matsunit = r1.Field<string>("matsunit").Trim(),
matcolor = r1.Field<string>("matcolor").Trim(),
asn_sqty1 = r1.Field<decimal>("asn_sqty"),
asn_sqty2 = r2 == null ? 0 : r2.Field<decimal>("asn_sqty"),
isAct = r2 == null ? 1 : 2,
};

這里如何優化下寫法,可以不用寫那麼多條件(equals 那裡,或者全部幫我重新寫過)。
如資料說:
如果有复杂的比较需求,建议自定义一个类型来作为比较键,用一个方法来获取:
from element1 in set1 join element2 in set2 on element1.GetKey() equals element2.GetKey()
小贴士:GetKey()可以是一个扩展方法。
問題點是:
如何寫這個GetKey() 方法.
謝謝!

...全文
86 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
exception92 2014-07-10
  • 打赏
  • 举报
回复
四个对比字段不算多。

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧