0

I have a list that I want to generate a query from. I need to get back the items that match each entry in my list and the list uses two values to match against the database. Manually created code would be like this pattern...

    from x in Context.Items
    where (x.Prop1 == 5 && x.Prop2 == "Foo") ||
          (x.Prop1 == 2 && x.Prop2 == "Bar") ||
          (x.Prop1 == 9 && x.Prop2 == "Etc")
    select x

If I only wanted to compare a single property I would just use the 'list.Contains(x => x.Prop1)' approach but I need to compare on two values and not one. Any ideas?

Phil Wright
  • 22,580
  • 14
  • 83
  • 137
  • There is no out-of-the-box solution. You have to build dynamically predicate expression similar to the manually written. – Ivan Stoev Aug 01 '20 at 06:59
  • 1
    Questions like this are usually closed as duplicate of https://stackoverflow.com/questions/26198860/entityframework-contains-query-of-composite-key/26201371#26201371. The answer by Gert Arnold provides all options. https://stackoverflow.com/questions/39306435/linq-expression-that-will-match-multiple-bulk-inputs?noredirect=1&lq=1 is an example of dynamic expression approach. – Ivan Stoev Aug 01 '20 at 07:10

1 Answers1

0

There is a few easy ways to do it and there are better answers if you search for it. This is my version based on, if the "list" model contains Prop1 and Prop2.

  • First Solution - This gets Prop1 and Prop2 into their own lists.

         var getProp1List = list.Select(i => i.Prop1).ToList();
         var getProp2List = list.Select(i => i.Prop2).ToList();
    
         var results = queryList.Where(i => getProp1List.Contains(i.Prop1) && getProp2List.Contains(i.Prop2)).ToList();
    
  • Second Solution - This selects multiple objects into one list.

         var getSearchTerms = list.Select(i => new { i.Prop1, i.Prop2 }).ToList();
    
         var results = queryList.Where(i => getSearchTerms.Select(x=>x.Prop1).Contains(i.Prop1) && getSearchTerms.Select(x => x.Prop2).Contains(i.Prop2)).ToList();
    
  • Third Solution - Simplest - Uses gets the lists of data using select from original list.

       var results = queryList.Where(i => list.Select(x=>x.Prop1).Contains(i.Prop1) && 
       list.Select(x => x.Prop2).Contains(i.Prop2)).ToList();
    

And that's if I have, understood the question properly!!

MacKey
  • 78
  • 2
  • 9