C# 如何在引用字段中连接两个具有空值的表
表t1(“PO1”)和表t2(“DTM”)包含以下值C# 如何在引用字段中连接两个具有空值的表,c#,linq,.net-4.5,C#,Linq,.net 4.5,表t1(“PO1”)和表t2(“DTM”)包含以下值 Table t1 PO101(string) Loop_Id (Int) Item_1 6 Item_2 8 --- Table t2 DTM02(string) Loop_Id(int) 20141029 (null) 20141029 6 20141101 8 这个问题 var re
Table t1
PO101(string) Loop_Id (Int)
Item_1 6
Item_2 8
---
Table t2
DTM02(string) Loop_Id(int)
20141029 (null)
20141029 6
20141101 8
这个问题
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable()
join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable()
on t1.Field<string>("Loop_Id") equals t2.Field<string>("Loop_Id")
select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")});
由于t2.Loop\u id中的空值
如果我删除t2中包含null值的行,它可以正常工作
如何将循环\u Id强制转换为可空的,或避免连接任何一个表中具有空的行?var records=(来自x12.interchangedDataSet.Tables[“PO1”]中的t1.AsEnumerable()
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable()
join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable()
on t1.Field<string>("Loop_Id")
equals (t2.Field<string>("Loop_Id") == null
? string.Emtpty : t2.Field<string>("Loop_Id"))
select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")});
在x12.InterchangeDataSet.Tables[“DTM”].AsEnumerable()中连接t2
在t1.字段上(“循环Id”)
等于(t2.字段(“循环Id”)==null
?string.Emtpty:t2.字段(“循环Id”))
选择新的{A=t1.Field(“PO101”),B=t2.Field(“DTM02”)};
我认为应该行得通。请尝试。使用下面的查询来处理null
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable()
join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable()
on t1.Field<int>("Loop_Id") equals t2.Field<int>("Loop_Id")
where t2.Field<int>("Loop_Id") != null
select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")});
var记录=(来自x12.InterchangeDataSet.Tables[“PO1”]中的t1.AsEnumerable()
在x12.InterchangeDataSet.Tables[“DTM”].AsEnumerable()中连接t2
在t1上,字段(“循环Id”)等于t2.字段(“循环Id”)
其中t2.字段(“循环Id”)!=null
选择新的{A=t1.Field(“PO101”),B=t2.Field(“DTM02”)};
以下是解决方案
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable()
join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() on t1.Field<Nullable<int>>("Loop_Id")
equals (t2.Field<Nullable<int>>("Loop_Id"))
select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")}
);
var记录=(来自x12.InterchangeDataSet.Tables[“PO1”]中的t1.AsEnumerable()
在t1.Field(“Loop_Id”)上的x12.InterchangeDataSet.Tables[“DTM”].AsEnumerable()中联接t2
等于(t2.字段(“循环Id”))
选择新的{A=t1.Field(“PO101”),B=t2.Field(“DTM02”)}
);
base{System.SystemException}={“无法将'System.Int32'类型的对象强制转换为'System.String'”}不,现在它抛出:{“无法将DBNull.Value强制转换为'System.Int32'类型。请使用可为null的类型。”}@paqoginez,这是从您的答案派生出来的,谢谢。正如您所见,使用静态nullable cast也消除了对where子句的需要。@paqogomez,我再也看不到您的答案了!。
var records = (from t1 in x12.InterchangeDataSet.Tables["PO1"].AsEnumerable()
join t2 in x12.InterchangeDataSet.Tables["DTM"].AsEnumerable() on t1.Field<Nullable<int>>("Loop_Id")
equals (t2.Field<Nullable<int>>("Loop_Id"))
select new{A = t1.Field<string>("PO101"),B=t2.Field<string>("DTM02")}
);