Linq To Entities Compare Value Against List<int>

只愿长相守 提交于 2019-12-01 11:45:55

Use the Contains function, it will match each ID against the given list:

return _UoW.tblcoursebookingRepo.All
       .Where(cb => AttendanceIDs.Contains(cb.Attended))
       .ToList();

In general, just keep in mind that a Where clause is nothing more than a fancy foreach with a nested if-statement (a very fancy one, though). It needs an expression that evaluates to a boolean. If you only had one item to check, without using LinQ, you'd quickly come up with something like:

if(AttendanceIDs.Contains(myItem.Attended))

You can treat LinQ's Where clauses in exactly the same way, as shown above :) If you're stumped, just think of how you would check it a single time, because LinQ will do the iterative part for you.

Update

As mentioned in Faisal's answer, WhereIn provides a similar functionality. Haven't used it yet, but it seems a more concise approach.

I'm not changing my answer though, as I feel it is more important to point out how you can use the boolean evaluation in a Where clause, this should also help for all future similar issues you might encounter where a WhereIn will not be relevant.

But nonetheless, you could as well use WhereIn in this particular case :-)

fhnaseer

You need to use WhereIn.

public static void Main()
{
  using (MyObjectContext context = new MyObjectContext())
  {
    //Using method 1 - collection provided as collection
    var contacts1 =
      context.Contacts.WhereIn(c => c.Name, GetContactNames());

    //Using method 2 - collection provided statically
    var contacts2 = context.Contacts.WhereIn(c => c.Name,
      "Contact1",
      "Contact2",
      "Contact3",
      "Contact4"
      );
  }
}

'Contains()' workaround using Linq to Entities?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!