使用LINQ.Dynamic对Null属性进行过滤会引发异常

时间:2015-12-04 18:27:47

标签: linq exception filter

我正在使用Linq.Dynamic,我有一个Tier列表(字符串Matricule,字符串Nom ..)虽然有些Tiers没有Matricule,但是当运行LINQ在Matricule属性上面时,System.NullReferenceException:Object reference not not设置为一个对象的实例被抛出? 这是代码的细节:

public class Tier
{
    public string Matricule{get;set;}
    public string Nom{get;set;}
    public string Prenom{get;set;}
}

public class FilterByPredicate
    {
        public BindingList<T> Filter(string propName,string propValue,bool fromFirst)
            {

                var predicateString = fromFirst
                                ? "{0}.ToString().ToUpper().StartsWith(@{1})"
                                : "{0}ToString().ToUpper().Contains(@{1})";

                return new BindingList<T>(_list.Where(string.Format(predicateString, propName, 0), propValue.ToUpper()).ToList());
            }

     }


in other part of my code i call..
    FilterByPredicate fbp = new FilterByPredicate(costumersList>);
    textBox1_Changed+=
    { 
       tiersBindingSource.DataSource =fbp .Filter("Matricule", textBox1.Text,true);// exception throwed

//but this work fine-> var q = from c in costumersList where c.Matricule.ToUpper().StartsWith(textBox1.Text) select c;
    };

1 个答案:

答案 0 :(得分:0)

我在阅读了文档后找到了解决方案,对应于&#34;开始使用&#34;页面,简单地比较为null:

 public BindingList<T> Filter(string propName,string propValue,bool fromFirst)
            {

                var predicateString = fromFirst
                                ? "{0} != null and {0}.ToString().ToUpper().StartsWith(@{1})"
                                : "{0} != null and {0}.ToString().ToUpper().Contains(@{1})";

                return new BindingList<T>(_list.Where(string.Format(predicateString, propName, 0), propValue.ToUpper()).ToList());
            }