0

I have a list of Ids and I only want to do an AND on the first one and and OR on the subsequent ones. In the past, I have kept a counter variable and when the counter is 1, I do the And, but after that I do an OR, but I was curious if there was an easier way:

foreach(string id in Ids)
{
   predicate.And(x=> id.Contains(x.id)); //I want to do an And only on the first id.
}

This is what I have done in the past, but is there a more concise way:

int counter = 1;
foreach (var Id in Ids)
{
     string i = Id;
     if (counter == 1)
     {
         predicate = predicate.And(x => i.Contains(x.id));
         counter++;
      }
      else
      {
           predicate = predicate.Or(x=>i.Contains(x.id));
          counter++;
      }
   }
Xaisoft
  • 45,655
  • 87
  • 279
  • 432

1 Answers1

1

This works with a local copy of PredicateBuilder (no entityFramework or LinkToSql available at work):

var firstID = ids.First();
predicate.And(x => firstID.Contains(x.id));

foreach (string id in ids.Skip(1))
{
    var localID = id;   //access to a modified closure otherwise
    predicate.Or(x => localID.Contains(x.id)); 
}
Pondidum
  • 11,457
  • 8
  • 50
  • 69
  • The one with And gives me the errror: `{"Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context."}`. ids is a string[] – Xaisoft May 30 '13 at 15:00
  • @xaisoft: which line gives that error? the `And` or the `Or`? – Pondidum May 30 '13 at 15:08
  • @Pondidum Probably the first. Just call `ids.First()` outside of the lambda so that it isn't compiled into the expression. – Servy May 30 '13 at 15:09
  • @Servy: yeah, I am just writing a testapp to check it first – Pondidum May 30 '13 at 15:13
  • This works, but it works just like my original way with just using a string.Contains. – Xaisoft May 30 '13 at 15:34
  • @Pondidum - Ok, I just changed the contains to == because since I am now iterating over each id, contains brought back incorrect results where == did not. Thanks! – Xaisoft May 30 '13 at 17:28