0

我正在尝试使用 LINQ 过滤 DataTable

DataTable DT=new DataTable();
DT = PinDicDAO.GetContractPOVD().AsEnumerable().Where(r => (r.Field<string>("ContractPOReference").ToUpper().Contains(text.ToUpper())) || (r.Field<string>("ContractPO").ToUpper().Contains(text.ToUpper())) ||
                                   (r.Field<string>("ContractPOTitle").ToUpper().Contains(text.ToUpper())) || (r.Field<string>("Address").ToUpper().Contains(text.ToUpper()))
                                   ).AsDataView().ToTable();

查询工作正常。但是当某些字段具有 NULL 值时,它会给出异常。

"Object Reference Not set to an instance of object"

我怎样才能避免这个异常?

4

1 回答 1

1

在尝试使用它之前检查空值。您最好使用 linq 关键字,这样您就可以使用 let 并使其更具可读性:

var query = from r in PinDicDAO.GetContractPOVD().AsEnumerable()
                        let ContractPOReference = r.Field<string>("ContractPOReference")
                        let ContractPO = r.Field<string>("ContractPO")
                        let ContractPOTitle = r.Field<string>("ContractPOTitle")
                        let Address = r.Field<string>("Address")
                        where (ContractPOReference != null && ContractPOReference.ToUpper().Contains(text.ToUpper())) ||
                           (ContractPO != null && ContractPO.ToUpper().Contains(text.ToUpper())) ||
                           (ContractPOTitle != null && ContractPOTitle.ToUpper().Contains(text.ToUpper())) ||
                           (Address != null && Address.ToUpper().Contains(text.ToUpper()))
                        select r;

            DT = query.AsDataView().ToTable();
于 2012-07-13T11:32:12.320 回答