当我在记录中有空值时,我在连接表时遇到问题。
有2个dataTables:
所以我开始这样的代码:
var record = from transaction in dtTransactions.AsEnumerable()
join worker1 in dtWorkers.AsEnumerable() on (int)transactions["worker1"] equals (int)worker1["workerID"]
join worker2 in dtWorkers.AsEnumerable() on (int)transactions["worker2"] equals (int)worker2["workerID"]
select new
{
ID = (int)transactions["transactionID"],
Name1= worker1["workerName"],
Name2= worker2["workerName"]
};
因此,如果worker2不为null,那么一切正常,但是当我有一个空值时,它无法连接。有人可以帮我解决这个问题,如果在dataTable中为null,我想有一个没有worker2名称的结果记录。
有可能吗?
答案 0 :(得分:1)
你需要做这样的左连接;
var record = from transaction in dtTransactions.AsEnumerable()
join worker1 in dtWorkers.AsEnumerable() on (int)transactions["worker1"] equals (int)worker1["workerID"]
join worker2 in dtWorkers.AsEnumerable() on (int)transactions["worker2"] equals (int)worker2["workerID"] into w2
from wrk in w2.DefaultIfEmpty()
select new
{
ID = (int)transactions["transactionID"],
Name1= worker1["workerName"],
Name2= wrk["workerName"]
};
其次,你有没有理由不指定像这样的对象属性;
var record = from transaction in dtTransactions.AsEnumerable()
join worker1 in dtWorkers.AsEnumerable() on (int)transactions.worker1 equals (int)worker1.workerID
join worker2 in dtWorkers.AsEnumerable() on (int)transactions.worker2 equals (int)worker2.workerID into w2
from wrk in w2.DefaultIfEmpty()
select new
{
ID = (int)transactions.transactionID,
Name1= worker1.workerName,
Name2= wrk != null ? wrk.workerName : ""
};
请注意删除方括号
答案 1 :(得分:0)
from x in left
where x.Id != null
join y in right on x.Id equals y.Id into rightMatches
from y2 in rightMatches.DefaultIfEmpty()
select new {x, y2};