处理LINQ查询中的空字节数组值

时间:2010-08-31 02:43:24

标签: c# linq linq-to-sql c#-4.0

我有以下LINQ代码:

docTypes = (from c in context.Citizenships join
            cdt in context.Citizenship_Document_Types 
                       on c.Country_Code equals cdt.Country_Code
            from cd in context.Citizenship_Documents
                              .Where(cd => cd.Citizenship_Id == c.Citizenship_ID)
                              .DefaultIfEmpty()
            where c.Citizenship_ID == citizenshipId
            select new CitizenshipDocument
    {
                Id = (int?)cd.Citizenship_Document_Id??-1,
                CitizenshipId = c.Citizenship_ID,
                DocumentTypeId = cdt.Citizenship_Document_Type_Id,
                DocumentTypeName = cdt.Citizenship_Document_Type_Name,
                DocumentCode = cd.Citizenship_Document_Code.ToArray(),
                ExpirationDate = cd.Expiration_Date,
                IssueDate = cd.Issue_Date
    }).ToList();

问题是,当cd.Citizenship_Document_Code返回null时,使用.ToArray()时会出错。 :

  

对象引用未设置为Object的实例

如何处理空值?

2 个答案:

答案 0 :(得分:1)

您将在LINQ查询中处理空值,就像在其他地方处理它们一样。不要取消引用空值!例如:

docTypes = (from c in context.Citizenships join
            cdt in context.Citizenship_Document_Types
            on c.Country_Code equals cdt.Country_Code
            from cd in context.Citizenship_Documents.Where(
                cd => cd.Citizenship_Id == c.Citizenship_ID).DefaultIfEmpty()
            where c.Citizenship_ID == citizenshipId
            select new CitizenshipDocument
            {
                Id = (int?)cd.Citizenship_Document_Id??-1,
                CitizenshipId = c.Citizenship_ID,
                DocumentTypeId = cdt.Citizenship_Document_Type_Id,
                DocumentTypeName = cdt.Citizenship_Document_Type_Name,
                DocumentCode = cd.Citizenship_Document_Code == null ?
                    null : 
                    cd.Citizenship_Document_Code.ToArray(),
                ExpirationDate = cd.Expiration_Date,
                IssueDate = cd.Issue_Date
            }).ToList();

答案 1 :(得分:0)

考虑使用类似以下扩展方法的方法使用适当的null对象处理null:

public static T ToNonNull<T>(this T input) where T : class, new()
{
  if (input != null)
  {
    return input;
  }
  return new T();
}

用法如下:

DocumentCode = cd.Citizenship_Document_Code.ToNonNull().ToArray()

如果您不想使用通用扩展名,也可以为该类型添加特定的ToNonNull()扩展名。