LINQ 和 ArrayList 的使用
我最近
在以下代码中使用了 LINQ:
ArrayList list = new ArrayList();
var myStrings = list.AsQueryable().Cast<string>();
AsQueryable
的用途是什么?我知道 Cast
创建类型安全的集合,并且 ArrayList
已弃用。
我有一个朋友说他需要将 AsQueryable
与 ArrayList
结合起来。我试图理解为什么,但我不明白为什么需要 AsQueryable
。
他错了吗?
I've recently used LINQ
In the following code:
ArrayList list = new ArrayList();
var myStrings = list.AsQueryable().Cast<string>();
What is the AsQueryable
for? I know Cast
creates a type-safe collection, and ArrayList
is deprecated.
I've got a friend who says he needs the AsQueryable
combined with ArrayList
. I'm trying to understand why, but I can't see why AsQueryable
is needed.
Is he wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要调用
AsQueryable()
。仅当 LINQ 查询(用 C# 表示)需要转换为另一种域语言(例如 SQL)时,可查询才有意义。在您的情况下,由于您正在使用 LINQ to Objects(您正在操作数组列表),因此不需要这样做。您可以直接在列表实例上调用
Cast()
方法。另一种选择是从强类型集合开始,例如List
。You do not need the call to
AsQueryable()
. Queryables only make sense when a LINQ query (expressed in C#) needs to be converted to another domain language (such as SQL). In your case since you are working with LINQ to Objects (you are operating on an array list) this is not needed.You can call the
Cast<T>()
method directly on the list instance. Another choice would be to start with a strongly-typed collection such asList<T>
.AsQueryable 将用于生成 IQueryable,如果实现的话,它可以通过表达式树分析查询以重写它或将其翻译成其他语言,例如 linq to sql。
在这种情况下,这是完全没有意义的,你可以告诉你的朋友不要打扰。
AsQueryable would be used to produce an IQueryable which can then, if implemented, analyse the query via expression trees to rewrite it or translate it into some other language-like with linq to sql for example.
In this case it is completely pointless and you can tell your friend not to bother.
使用
AsQueryable()
的唯一作用是使查询结果的静态类型为IQueryable
。无论如何,这对于对象来说确实毫无用处。您真正需要的只是:
没有
AsQueryable()
。那么结果的类型就是IEnumerable
。或者更好的是,获取强类型
List
:The only effect the use of
AsQueryable()
has here is to make the static type of the result of the query isIQueryable<string>
. For all intents and purposes, this is really useless on an object.You only really need:
without the
AsQueryable()
. Then the type of the result is justIEnumerable<string>
.Or better yet, to get a strongly typed
List<string>
: