问题
I am using Entity Framework 5.0, and I have a problem with a LINQ query. I have the following method that accepts an integer value which is then passed into the query. This works fine.
public IList<tblcoursebooking> GetStandardReport(int AttendanceID)
{
return _UoW.tblcoursebookingRepo.All
.Where(cb => cb.Attended.Equals(AttendanceID)
.ToList();
}
However, I need to change the method so that it accepts a List of integers, and then pulls out all records where Attended is equal to any of the List of integers. Something like this
public IList<tblcoursebooking> GetStandardReport(List<int> AttendanceIDs)
{
return _UoW.tblcoursebookingRepo.All
.Where(cb => cb.Attended.Equals == any AttendanceIDs
.ToList();
}
I would like to do try and use the Contains or Any LINQ keywords, however, as Attended is a single value, not a collection, the only properties available to me after the dot are
CompareTo, Equals, GetHashCode, GetType, GetTypeCode, ToString
Could someone please help?
Thanks for your time.
回答1:
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 :-)
回答2:
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?
来源:https://stackoverflow.com/questions/15829031/linq-to-entities-compare-value-against-listint