如何将 LINQ 列表更改为数组列表
我必须使用 LINQ 在 Web 应用程序中编写查询,但我需要将该查询更改为数组列表。我如何更改下面的查询来执行此操作?
var resultsQuery =
from result in o["SearchResponse"]["Web"]["Results"].Children()
select new
{
Url = result.Value<string>("Url").ToString(),
Title = result.Value<string>("Title").ToString(),
Content = result.Value<string>("Description").ToString()
};
I have to write a query in a web application using LINQ but I need to change that query into an array list. How can I change the query below to do this?
var resultsQuery =
from result in o["SearchResponse"]["Web"]["Results"].Children()
select new
{
Url = result.Value<string>("Url").ToString(),
Title = result.Value<string>("Title").ToString(),
Content = result.Value<string>("Description").ToString()
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你确实需要创建一个ArrayList,你可以编写
new ArrayList(resultsQuery.ToArray())
。但是,您应该通过编写
resultsQuery.ToList()
来使用List
。请注意,在这两种情况下,列表都将包含匿名类型的对象。
If you really need to create an ArrayList, you can write
new ArrayList(resultsQuery.ToArray())
.However, you should use a
List<T>
instead, by writingresultsQuery.ToList()
.Note that, in both cases, the list will contain objects of anonymous type.
有一个 .ToArray() 方法可以将 IEnumerable 转换为数组。
There is a .ToArray() method that'll convert IEnumerable to an Array.
ArrayList
没有构造函数或采用IEnumerable
的 Add(Range) 方法。因此,剩下两个选择:使用实现了
ICollection
的中间集合:因为Array
和List
都实现了ICollection
可以通过 LINQ 中的ToArray()
或ToList()
扩展方法来使用。创建
ArrayList
的实例,然后添加结果的每个元素:前一种方法很简单,但确实意味着创建中间数据结构(这两个选项中的哪一个)具有更高的开销是一个有趣的问题,部分取决于查询,因此没有通用答案)。后者需要更多代码,并且确实涉及增量增长 ArrayList(因此 GC 需要更多内存,就像中间 ArrayList 或 List的情况一样) ;)。
如果您只需要在一个地方执行此操作,则可以内联执行代码,如果您需要在多个位置执行此操作,请通过
IEnumerable
创建您自己的扩展方法:ArrayList
doesn't have a constructor or Add(Range) method that takes anIEnumerable
. So that leaves two choices:Use an intermediate collection that does implement
ICollection
: as bothArray
andList<T>
implementICollection
can be used via theToArray()
orToList()
extension methods from LINQ.Create an instance of
ArrayList
and then add each element of the result:The former method is simple to do but does mean creating the intermediate data structure (which of the two options has a higher overhead is an interesting question and partly depends on the query so there is no general answer). The latter is more code and does involve growing the
ArrayList
incrementally (so more memory for the GC, as would be the case for an intermediateArray
orList<T>
).If you just need this in one place you can just do the code inline, if you need to do it in multiple places create your own extension method over
IEnumerable<T>
: