C# 具有多个属性(其中一些属性为空)的LINQ查询
我在.NET4.5框架中使用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));
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