Use of LINQ and ArrayList

前端 未结 3 1078
借酒劲吻你
借酒劲吻你 2021-01-05 10:42

I\'ve recently used LINQ

In the following code:

ArrayList list = new ArrayList();
var myStrings = list.AsQueryable().Cast();

相关标签:
3条回答
  • 2021-01-05 10:56

    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.

    0 讨论(0)
  • 2021-01-05 11:10

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

    0 讨论(0)
  • 2021-01-05 11:12

    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 讨论(0)
提交回复
热议问题