Using a List as a condition for LINQ to SQL query

2019-07-16 07:24发布

问题:

I have a LINQ to SQL query that goes like this:

String NameCondition = "Test";
String EmailCondition = "test@test.com";

IQueryable<User> Users = Repository.Where(x => x.Name.Equals(NameCondition) && x.Email.Equals(EmailCondition));

But now I have a list of conditions where I would like to pull Users from if they match any of them (like an OR statement in SQL). So I have a list of dictionaries, and each dictionary is a condition with a name and email:

List<Dictionary<String, String>> Conditions;

How can I perform a LINQ to SQL query using those conditions?

回答1:

Use PredicateBuilder by Josef Albahari

http://www.albahari.com/nutshell/predicatebuilder.aspx

Here is a sample usage.

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}


回答2:

Instead of dictionary use List<KeyValuePair<string, string>> in .NET 3.5 and List<Tuple<string, string>> in .NET 4.0.

See some kind similar question