I am getting some behavior from a LINQ Where clause that I can't quite grok.
For instance, I am trying to search a list for terms using a AND semantic.
Here is some code:
var items = new List<string>()
{
"beef",
"beef soup",
"beef ribs",
"chicken soup",
"soup",
"pork ribs",
"ribs"
};
var term = "soup beef";
var terms = term.Split(' ');
var result = items.AsQueryable();
foreach(var t in terms)
{
result = result.Where( i => i.Contains(t) );
}
result.ToList().Dump();
The result are:
- beef beef
- soup
- beef ribs
However, I was looking for it to an AND result, returning just:
- beef soup
Now, I CAN GET THE RESULT I WANT by simply adding
.ToList().AsQueryable()
to the end of the Where clause.
Of course, this is not what I want to do if the back end is a database.
What is really odd here is that when I check 'result' in the loop, I get the following:
- Before first where clause => full list -> makes sense.
- After first where (for 'soup') => ['beef soup', 'chicken soup', 'soup'] -> still looks good
- Before second loop (for 'beef') => ['beef', 'beef soup', 'beef ribs'] -> WHOA! Whats up here
- After second loop => stays the same
Can someone explain to me what is going on (and how to fix this correctly)?