开发者

Use of LINQ and ArrayList

开发者 https://www.devze.com 2023-02-12 05:46 出处:网络
I\'ve recently used LINQ In the following code: ArrayList list = new ArrayList(); var myStrings = list.AsQueryable().Cast<string>();

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 fri开发者_StackOverflow中文版end 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?


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 as List<T>.


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.


The only effect the use of AsQueryable() has here is to make the static type of the result of the query is IQueryable<string>. For all intents and purposes, this is really useless on an object.

You only really need:

var myStrings = list.Cast<string>();

without the AsQueryable(). Then the type of the result is just IEnumerable<string>.

Or better yet, to get a strongly typed List<string>:

var myStrings = list.Cast<string>().ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消