2

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Alan L
  • 133
  • 1
  • 2
  • 8
  • 1
    Why do you have a list of dictionaries? It sounds like you're saying that each dictionary only contains one entry. Is that the case? – Daniel Pratt Dec 22 '10 at 15:18

2 Answers2

0

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);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
  • 2
    why the edit Daniel.?? i thought the usage example supported the link well – jim tollan Dec 22 '10 at 15:22
  • @jim It's joyful to use the privileges :-) – Jahan Zinedine Dec 22 '10 at 15:24
  • ab(use) in my case probably :-) – jim tollan Dec 22 '10 at 15:27
  • Something strange is going on. I don't remember if the example was in the version I edited, however I definitely did not remove it. I only altered the formatting of the link. It was originally backtick-quoted, which caused the link not to work. – Daniel Pratt Dec 22 '10 at 16:05
  • I think this is a result of the '5-minute window' feature of SO: http://meta.stackexchange.com/questions/9090/is-there-an-editing-grace-period-on-answers-after-they-have-been-posted – Daniel Pratt Dec 22 '10 at 16:16
0

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

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433