Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有多个属性(其中一些属性为空)的LINQ查询_C#_Linq - Fatal编程技术网

C# 具有多个属性(其中一些属性为空)的LINQ查询

C# 具有多个属性(其中一些属性为空)的LINQ查询,c#,linq,C#,Linq,我在.NET4.5框架中使用C#创建了一个LINQ查询 查询通过将字符串FilterInput与多个属性(所有类型均为string: tempList = tempList.FindAll(w => w.Number.Contains(FilterInput) || w.SN.Contains(FilterInput) || w.Model.Contains(FilterInput) || w.Location.Contains(FilterInput));

我在.NET4.5框架中使用C#创建了一个LINQ查询

查询通过将字符串
FilterInput
与多个属性(所有类型均为string:

tempList = tempList.FindAll(w =>
    w.Number.Contains(FilterInput) ||
    w.SN.Contains(FilterInput) ||
    w.Model.Contains(FilterInput) ||
    w.Location.Contains(FilterInput));
因此,如果
FilterInput
是“ABC”,它将包括(作为几个可能的示例):

  • w、 数字==“ABCD”
  • w、 序号==“01234ABC”
  • w、 模型==“ABC”
  • w、 地点==“ABC有限公司”
一切进展顺利,直到查询在包含字符串属性的
null
的属性上运行:

  • w、 SN==
    null

    (请注意,如果w.SN==“null”,这不是相同的问题,并且不会引发相同的错误)
有没有办法绕过此语句中的
null
属性,而不重构
w
的属性


顺便说一句,我还没有在MSDN的有用站点“”上找到任何东西…

尝试添加
w.SN!=空&

tempList = tempList.FindAll(w =>
    w.Number.Contains(FilterInput) ||
    w.SN !=null && w.SN.Contains(FilterInput) ||
    w.Model.Contains(FilterInput) ||
    w.Location.Contains(FilterInput));

如果其他参数(
w.Number
w.Model
w.Location
)也可以
null
,则需要添加类似的检查。

无论类属性的数量如何:

例如:

public class test
{
    public string p1 { get; set; }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public int p4 { get; set; }
}


如果您使用的是
FindAll
,那么您根本没有使用LINQ。
test t1 = new test
{
    p1 = null,
    p2 = "test1",
    p3 = "test2",
    p4 = 0
};
test t2 = new test
{
    p1 = "test1",
    p2 = "test2",
    p3 = "test3",
    p4 = 0
};
test t3 = new test
{
    p1 = "test1",
    p2 = "tst2",
    p3 = "test3",
    p4 = 0
};

string filterInput = "test";
var testStringProperties = typeof(test)
                           .GetProperties()
                           .Where(p => p.PropertyType == typeof(string));
var a1 = testStringProperties.All(p =>
{
    string tempValue = (string)p.GetValue(t1);
    return tempValue != null && tempValue.Contains(filterInput);
});
var a2 = testStringProperties.All(p =>
{
    string tempValue = (string)p.GetValue(t2);
    return tempValue != null && tempValue.Contains(filterInput);
});
var a3 = testStringProperties.All(p =>
{
    string tempValue = (string)p.GetValue(t3);
    return tempValue != null && tempValue.Contains(filterInput);
});
//a1=false
//a2=true
//a3=false