I have a table that contains objects from type person, each person has a unique column of type string called id
, and I have a hashset of Id
's that I want to fetch the person's object for.
I thought I could do it efficiently by doing this:
HashSet<string> ids = //Some HashSet of ids
var idsHashSet = DbContext.Persons.Select(p => p.Id).ToHashSet();
idsHashSet.IntersectWith(ids);
var result = DbContext.Persons.Where(p => idsHashSet.Contains(p.Id)).ToList());
I saw in the database itself that the query being sent is:
SELECT <something>
FROM <something>
WHERE p.name IN ('id1', 'id2', id3'...)
And it's not efficient because I already know that each element in the HashSet is present in the database, so I wanted to know, is there a more efficient way to do it?