List、IList、IEnumerable、IQueryable、ICollection,哪种返回类型最灵活? [英] List, IList, IEnumerable, IQueryable, ICollection, which is most flexible return type?

查看:27
本文介绍了List、IList、IEnumerable、IQueryable、ICollection,哪种返回类型最灵活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前在这里看到过这个问题,但我不满意我了解完整的后果.问题是使用 linq-to-sql 的数据层应该返回什么类型,以获得最大的灵活性和查询能力.这是我读过/发现的:

I've seen this question posted here previously but I'm not satisfied that I understand the complete ramifications. The problem is what return type should a data layer that uses linq-to-sql return for maximum flexibility and query ability. This is what I've read/found:

  1. IEnumerable 是有限的,只允许向前读操作.IEnumerable 是最通用的.我发现 IEnumerable 确实允许查询操作与扩展语法.

  1. IEnumerable is limited and only allows for read forward operation. IEnumerable is the most generic. What I've found is that IEnumerable does allow query operations vs the extension syntax.

由于插入操作,列表允许最大的灵活性.

List allows for most flexibility because of insert operations.

应该使用集合而不是列表来启用只读集合.

Collections should be used instead of list to enable read only collections.

IQueryable 不应该被使用,它应该被使用和关闭".IQueryable 不返回列表,而是为数据库生成查询语法.

IQueryable should never be used, it should be "used and turned off". IQueryable doesn't return a list but generates a query syntax for database.

我觉得我对权衡有更好的感觉,但仍然不确定一些事情:

I feel I have a better feel for the trade offs but still not sure about a few things:

  1. 为什么我会选择接口变体而不是具体类型?即 IList 或 ICollection 与列表或集合.我会得到什么好处?

  1. Why would I choose the interface variants over the concrete types? I.e IList or ICollection vs List or Collection. What benefit would I get?

我看到扩展操作有效,但扩展查询语法是否也有效?

I see that the extension operations work but will the expanded query syntax work as well?

之前有人建议我使用 AsQueryable().但是,如果我没有连接到数据库,我为什么要这样做呢?无论如何,扩展方法似乎都有效.

Someone suggested I use AsQueryable() before. But, why would I do this if I don't have connection to the database? It seems the extension methods work regardless.

推荐答案

集合对于 DAL 返回通常不是很有用,因为集合并不隐式地保证顺序.这只是一桶物品.另一方面,IList 确实隐式地保证了顺序.所以我们归结为 IEnumerable 或 IList.下一个问题是:List 对象是否活动"?即,它是否连接到数据后备,以便当您将项目添加到 IList 时,它将反映在数据库中?对于 LINQ-to-SQL,情况并非如此.相反,您应该将实体附加到表中.因此,除非您提供这种额外的接线,否则 List 是多余的.坚持使用 IEnumerable.

Collections are not generally very useful for DAL returns, because a collection does not implicitly guarantee order. It's just a bucket of items. An IList, on the other hand, does implicitly guarantee order. So we're down to IEnumerable or IList. The next question would be: is the List object "live"? i.e., is it connected to the data backing so that when you add an item to the IList, it will be reflected in the DB? For LINQ-to-SQL, this is not the case. Rather, you're supposed to attach entities to the tables. So unless you supply this additional wiring, a List is superfluous. Stick with IEnumerable.

这篇关于List、IList、IEnumerable、IQueryable、ICollection,哪种返回类型最灵活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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