使用以下代码,我如何获得包含任何zip列表但仅包含具有街道地址目的的记录的返回值?这将返回zip地址或街道地址的匹配项。
var zipPredicate = PredicateBuilder.False<NameAddress>();
List<string> zips = new List<string>();
zips.Add("90210");
zips.Add("90211");
foreach (var item in zips)
{
zipPredicate = zipPredicate.Or(n=> n.ZIP.Contains(item));
}
zipPredicate = zipPredicate.And(n=> n.Purpose=="Street Address");
var zipResult = from s in NameAddresses
.AsExpandable()
.Where(zipPredicate)
select new{s.ID, s.ZIP, s.Purpose};
zipResult.Dump();
我想你要找的是:
var zipPredicate = PredicateBuilder.False<NameAddress>();
List<string> zips = new List<string>();
zips.Add("90210");
zips.Add("90211");
foreach (var item in zips)
{
zipPredicate = zipPredicate.Or(n=> n.ZIP.Contains(item) && n.Purpose=="Street Address");
}
var zipResult = from s in NameAddresses
.AsExpandable()
.Where(zipPredicate)
select new{s.ID, s.ZIP, s.Purpose};
zipResult.Dump();
编辑
还有一件事,如果你想放弃构建谓词,你应该能够做这样的事情:.Where(n=>zips.Contains(n.ZIP) && n.Purpose=="Street Address")
重要的是你的实体属性组件在. contains()中。这会将代码缩短为:
List<string> zips = new List<string>();
zips.Add("90210");
zips.Add("90211");
var zipResult = from s in NameAddresses
.AsExpandable()
.Where(n=>zips.Contains(n.ZIP) && n.Purpose=="Street Address")
select new{s.ID, s.ZIP, s.Purpose};
zipResult.Dump();
我更喜欢它的可读性。我希望最终执行的查询是相同的。