Can I assign the result of a Linq query to the source variable of the same query?
For example, can I do this?
myList = myList.where(x=>x>10).select(x=>x-10);
where myList
is Enumerable<int>
I am worried that, as it is a lazy list, it might cause some problems, such as an infinite loop. (It might not in this case,开发者_开发百科 but would it happen in other cases?)
You may run into issues if you use type inferencing (var) if you specifically state that your return type is the underlying interface type then you should be ok. Select can return either IEnumerable or IQueryable (in the case of LINQ 2 SQL/EF). Thus if you instantiate it as follows, you should be ok:
IEnumerable<int> myList = nums;
myList = myList.Where(x => x > 10).Select(x => x - 10);
This is typically used when dynamically addng to the query based on user input as follows:
IEnumerable<int> myList = nums.OrderBy(x => x);
if (applyFilter)
myList = myList.Where(x => x > 10).Select(x => x - 10);
Notice if you instantiate your myList using var myList = nums in the above example, it would fail to compile because OrderBy returns IOrderedEnumerable and Where and Select return IEnumerable which would otherwise change the type of myList.
One other thing to be aware of if you take John Oxley's suggesting in using .ToEnumerable() on an IQueryable source (or mine above for that matter), it will force the fetching from the database and any subsequent query additions will be applied client side. If you want to keep it server side, declare it as IQueryable rather than IEnumerable.
You can as long as you convert the result back into the base type. If myList is IEnumerable you'd need to convert it with .AsEnumerable()
:
myList = myList.where(x=>x>10).select(x=>x-10).AsEnumerable();
There's no problem with that line. The right side will be evaluated before the assignment, so it's as innocuous as x = x + 1
where x
is just an int
.
精彩评论