Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

.net - List, IList, IEnumerable, IQueryable, ICollection, which is most flexible return type?

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

  2. List allows for most flexibility because of insert operations.

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

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...