你会ToList()吗? [英] Do you ToList()?
问题描述
您是否希望在处理LINQ查询结果时使用默认类型?
Do you have a default type that you prefer to use in your dealings with the results of LINQ queries?
默认情况下,LINQ将返回IEnumerable<>
或IOrderedEnumerable<>
.我们发现List<>
通常对我们更有用,因此习惯了大部分时间ToList()
进行查询,并且肯定在函数参数和返回值中使用List<>
.
By default LINQ will return an IEnumerable<>
or maybe an IOrderedEnumerable<>
. We have found that a List<>
is generally more useful to us, so have adopted a habit of ToList()
ing our queries most of the time, and certainly using List<>
in our function arguments and return values.
唯一的例外是在LINQ to SQL中,其中调用.ToList()
会过早枚举IEnumerable
.
The only exception to this has been in LINQ to SQL where calling .ToList()
would enumerate the IEnumerable
prematurely.
我们还广泛使用WCF,其默认集合类型为System.Array
.为了与代码库的其余部分保持一致,我们始终在VS2008的服务引用设置"对话框中将其更改为System.Collections.Generic.List
.
We are also using WCF extensively, the default collection type of which is System.Array
. We always change this to System.Collections.Generic.List
in the Service Reference Settings dialog in VS2008 for consistency with the rest of our codebase.
你做什么?
推荐答案
ToList
始终会立即评估序列-不仅仅是在LINQ to SQL中.如果您愿意的话,那很好-但这并不总是合适的.
ToList
always evaluates the sequence immediately - not just in LINQ to SQL. If you want that, that's fine - but it's not always appropriate.
就我个人而言,我会尽量避免声明您直接返回List<T>
-通常IList<T>
更合适,并且允许您稍后更改为其他实现.当然,有些操作只能在List<T>
本身上指定...这种决定总是很棘手.
Personally I would try to avoid declaring that you return List<T>
directly - usually IList<T>
is more appropriate, and allows you to change to a different implementation later on. Of course, there are some operations which are only specified on List<T>
itself... this sort of decision is always tricky.
(我会在注释中添加它,但它太庞大了.)延迟执行使您可以处理太大而无法容纳在内存中的数据源.例如,如果您正在处理日志文件-将其从一种格式转换为另一种格式,将其上传到数据库中,计算一些统计信息或类似内容-您很可能能够通过流化处理任意数量的数据,但是您真的不想想要将所有内容都吸收到内存中.对于您的特定应用程序,这可能不是要关心的问题,但是要牢记这一点.
(I would have put this in a comment, but it would be too bulky.) Deferred execution allows you to deal with data sources which are too big to fit in memory. For instance, if you're processing log files - transforming them from one format to another, uploading them into a database, working out some stats, or something like that - you may very well be able to handle arbitrary amounts of data by streaming it, but you really don't want to suck everything into memory. This may not be a concern for your particular application, but it's something to bear in mind.
这篇关于你会ToList()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!