I have a problem with looping through a set of XElements
. The behavior is not what I expected.
A short re-written version of my code, so you can easily get my problem (console app in C#)
IEnumerable<XElement> q = from c in xml.Descendants(aw + "wd")
where (....)
select c;
...
//--------------------------------------------------------------------
IEnumerable<XElement> currRow = q.OrderBy(yyy => (int)yyy.Attribute("t"));
int xValue = 10;
currRow = currRow.Where(yyy => (int)yyy.Attribute("t") < xValue);
xValue = 20;
//Here, the currRow gets a new value automatically. I don't want this!
//--------------------------------------------------------------------
//This is want i want to acheive:
IEnumerable<XElement> currRow = q.OrderBy(yyy => (int)yyy.Attribute("t"));
int xValue = 10;
currRow = currRow.Where(yyy => (int)yyy.Attribute("t") < xValue);
//do somthing with currRow
xValue = 20;
currRow = currRow.Where(yyy => (int)yyy.Attribute("t") < xValue);
//do somthing else with currRow
xValue = 30;
currRow = currRow.Where(yyy => (int)yyy.Attribute("t") < xValue);
// etc....
Any ideas?
currRow.Where(...)
Will create a query that will be executed when used.
If you want the result directly (and omitting any references/query to be screwed up) convert it to a list.
currRow.Where(...).ToList()
The reason why you should to this is because the value you use in your where statement isn't seen as a constant within the query but a reference to the variable you used. If you change the variable, you possibly changed the outcome of the query.
If you call .ToList()
the query is executed with the value of the variable on that moment. The result is gathered and is 'permanent' in such way that the query which was made to create the result won't be influencing the result any more when the value of the variable used in the query changes.