我可以将Linq查询的结果分配给同一查询的源变量吗? [英] Can I assign the result of a Linq query to the source variable of the same query?

查看:55
本文介绍了我可以将Linq查询的结果分配给同一查询的源变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我可以这样做吗?

For example, can I do this?

myList = myList.where(x=>x>10).select(x=>x-10);

其中myListEnumerable<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?)

推荐答案

如果您使用类型推断(var),并且特别声明返回类型为基础接口类型,则可能会遇到问题. Select可以返回IEnumerable或IQueryable(对于LINQ 2 SQL/EF).因此,如果您按以下方式实例化它,则应该没问题:

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);

请注意,如果在上面的示例中使用var myList = nums实例化myList,它将无法编译,因为OrderBy返回IOrderedEnumerable,而Where and Select返回IEnumerable,否则将更改myList的类型.

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.

要注意的另一件事是,如果您采用John Oxley的建议在IQueryable源(或上面的我的问题)上使用.ToEnumerable(),它将强制从数据库中进行获取,并且随后的所有查询添加将应用的客户端.如果要将其保留在服务器端,请将其声明为IQueryable而不是IEnumerable.

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.

这篇关于我可以将Linq查询的结果分配给同一查询的源变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆