Linq partial match in list?

不打扰是莪最后的温柔 提交于 2019-12-01 18:55:30

问题


I have a list of partial strings that I need to match in a table. I'm using PredicateBuilder.

var predicate = PredicateBuilder.False<Name>();
List<string> names = new List<string>();
names.Add("test name"); **<===matches**
names.Add("test"); **<=== doesn't match**
predicate = predicate.Or(n => names.Contains(n.Company));
var results = (from n in Names
.AsExpandable()
.Where(predicate)
select(new{ n.Company}));

n.Company = "test name"

This will match if the n.Company is exactly "test name" but it doesn't match if I just use "test". How do I match a partial on a list.Contains?


回答1:


You should change your code this way

var predicate = PredicateBuilder.False<Name>();
List<string> names = new List<string>();
names.Add("test name"); 
names.Add("test"); 
foreach(string name in names)    
{
    string temp = name;
    predicate = predicate.Or(n => n.Company.Contains(temp));
}
var results = (from n in Names 
    .AsExpandable()
    .Where(predicate)
    select(new{ n.Company}));


来源:https://stackoverflow.com/questions/14348586/linq-partial-match-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!