你 ToList() 吗? [英] Do you ToList()?

查看:10
本文介绍了你 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 - 通常 IList 更合适,并允许您更改为不同的稍后实施.当然,有些操作只在 List 本身上指定......这种决定总是很棘手.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆