5

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?

John S
  • 7,909
  • 21
  • 77
  • 145

1 Answers1

7

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}));
Esteban Elverdin
  • 3,552
  • 1
  • 17
  • 21
  • This is correct - I've verified it with the following Linqpad C# Statement - https://gist.github.com/4546570. Also, this looks very similar to first example on the main PredicateBuilder page - http://www.albahari.com/nutshell/predicatebuilder.aspx – Aaron Newton Jan 16 '13 at 11:40
  • I was thinking way to hard about this. Simple is always better. Thanks – John S Jan 16 '13 at 18:47