Reputation: 559
I have a search method that takes a list of ID's and I wish to restrict the query based on the ID's.
Param: IEnumerable filterType
foreach (int id in filterType)
{
query = query.Where(q => q.Item1 == id);
}
If I try:
foreach (int id in filterType)
{
query = query.Where(q => q.Item1 != id);
}
It seems to work.
Does anyone know why?
Thanks in advance.
Upvotes: 1
Views: 130
Reputation: 234664
By doing query = query.Where(q => q.Item1 == id);
, you're effectively building a query similar to the following:
query.Where(q => q.Item1 == id1)
.Where(q => q.Item1 == id2)
.Where(q => q.Item1 == id3)
.Where(q => q.Item1 == id4);
Which obviously won't return results: an item cannot have two different IDs.
You probably want:
query.Where(q = filterType.Contains(q.Item1));
Upvotes: 2
Reputation: 1503290
Multiple where
clauses are effectively "AND-ed" together - so if your filterType
list had 5 and 10 in, you'd be saying that Item1
had to be both 5 and 10, which it can't be simultaneously.
I suspect you actually want:
query = query.Where(q => filterType.Contains(q.Item1));
In other words, where Item1
matches one of the values in filterType
. (You might also want to consider the case where filterType
is empty. Should that match everything or nothing?)
Upvotes: 4