I’ll try to explain this well, as it’s quite strange.
I have a .NET MVC 4 app with Linq2SQL where I’m developing a search where users are able to seek elements by one or more different values.
I have a method that receive a string like: “value1&value2|value3&value4”
I pretend to return results where a determinated element contains value1 AND value2 OR that determinated element contains value3 AND value4.
I’m using an algorithm like this:
if (!String.IsNullOrEmpty(figuresSelected)) {
string[] groupsOR = figuresSelected.Split('|');
IQueryable<CENTROSOPERACIONES> sqlAuxOr = null;
foreach (string goupOR in groupsOR) {
string[] groupsAND = groupOR.Split('&');
IQueryable<CENTROSOPERACIONES>[] sqlAuxAnd = sql; //sql contains current query so far
foreach (string group in groupsAND) {
sqlAuxAnd = sqlAuxAnd.Where(o => o.CENTROS.FIGURASCENTROS.Any(f => f.FIGURAS.nombre == group));
}
if (sqlAuxAnd != null)
if (sqlAuxOr == null)
sqlAuxOr = sqlAuxAnd;
else
sqlAuxOr = sqlAuxOr.Union(sqlAuxAnd);
}
}
Well, the problem here is that, on every iteration inside the inner loop, sqlAuxAnd queries from the original data container on sql, not from the subresult obtained on the previous loop. I’ve followed the loop iteration by iteration and I’ve checked that sqlAuxAnd contains the expected subresult on the first iteration, but when reaching a second one that value is lost and a full query from the whole data is stored on it.
I’ve tried to store sqlAuxAnd partial results on different elements (I used an array) and checked it’s evolution. On the first iteration sqlAuxAnd[0] contains the expected result and sqlAuxAnd[1] is empty, on the second iteration both elements, sqlAuxAnd[0] and sqlAuxAnd[1] contains the expected result from querying the second value from the whole dataset.
It seems I’m losing something here… probably it’s something trivial, but I supose I’m too dizzy to see it. Anyone have any idea to share?
Feel free to ask for explanations on the matter, english is not my mother language and I supose that probably the question is not as well redacted as it should be.
You need to capture the
groupvariable from the foreach:See Linq query built in foreach loop always takes parameter value from last iteration.