PRASHANT P
PRASHANT P

Reputation: 1547

Use of LINQ and ArrayList

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?

Upvotes: 7

Views: 12498

Answers (3)

Jeff Mercado
Jeff Mercado

Reputation: 134841

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

Upvotes: 2

Andras Zoltan
Andras Zoltan

Reputation: 42343

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.

Upvotes: 3

marcind
marcind

Reputation: 53183

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>.

Upvotes: 13

Related Questions