error - 如果存在null值,则使用Linq连接两个数据表

时间:2016-11-11 20:09:56

标签: c# linq datatables

我有两个数据表,

 var userList1 = from myRow in dt.AsEnumerable()
                            where myRow.Field<bool?>("IsActive1") == null ? true : myRow.Field<bool?>("IsActive1") == true
                            select myRow;


            var userList2 = from myRow in dt1.AsEnumerable()
                            select myRow;

dt1表显示如下,

enter image description here

但是我希望从这个Linq查询中获取null UserId的docCount,

var objUserSetUp1 = (from A in userList1
                                 join B in userList2 on new { UserId = A.Field<Int64?>("Id") == null ? 0 : A.Field<Int64>("Id") } equals new { UserId = B.Field<Int64?>("UserId") == null ? 0 : B.Field<Int64>("UserId") }
                                 select new
                                 {
                                     UserId = A.Field<Int64>("Id"),
                                     FirstName = A.Field<string>("FirstName"),
                                     SurName = A.Field<string>("SurName"),
                                     Computer_Name = A.Field<string>("Computer_Name"),
                                     IP_Address = A.Field<string>("IP_Address"),
                                     LogInTime = A.Field<string>("LogInTime") == null ? "UnKnown" : A.Field<string>("LogInTime"),
                                     UserName = A.Field<string>("UserName"),
                                     Password = A.Field<string>("Password"),
                                     login_Id = A.Field<Int64?>("login_Id") == null ? 0 : A.Field<Int64?>("login_Id"),
                                     docCount = B.Field<Int64>("docCount")

                                 }).ToList();

但是它会引发错误。 “价值不能为空。”如何在objUserSetUp1中获取null UserId docCount并从objUserSetUp1对象中避免此异常?

1 个答案:

答案 0 :(得分:1)

您想要UserId不为空的所有计数吗?喜欢这个?

var objUserSetUp1 = (from A in userList1
                where A.Field<Int64>("Id") != null
                select new
                {
                    UserId = A.Field<Int64>("Id"),
                    FirstName = A.Field<string>("FirstName"),
                    SurName = A.Field<string>("SurName"),
                    Computer_Name = A.Field<string>("Computer_Name"),
                    IP_Address = A.Field<string>("IP_Address"),
                    LogInTime = A.Field<string>("LogInTime") == null ? "UnKnown" : A.Field<string>("LogInTime"),
                    UserName = A.Field<string>("UserName"),
                    Password = A.Field<string>("Password"),
                    login_Id = A.Field<Int64?>("login_Id") == null ? 0 : A.Field<Int64?>("login_Id"),
                    docCount = A.Field<Int64>("docCount")

                }).ToList();