简体   繁体   English

IEnumerable的 <T> VS IList <T> VS IQueryable <T>

[英]IEnumerable<T> VS IList<T> VS IQueryable<T>

New to the MVC.net scene (and .net for that matter), but seems I find a wide array of options when wanting to populate a "list" with data. MVC.net场景的新手(以及.net),但是当我想要用数据填充“列表”时,我似乎找到了各种各样的选项。 In my case at the moment, I'd like to populate a list from a select query of items and render the results in JSON for output, so bear with me.... 在我的情况下,我想从一个选择的项目查询中填充一个列表,并用JSON渲染结果输出,所以请耐心等待....

So, my viewmodel class is something like : 所以,我的viewmodel类是这样的:

[Serializable()]
public class TFSquery 
{
    public int MsgUid { get; set; }
    public DateTime CreateStamp { get; set; }    
}

And then I'd like to populate it with my query output: 然后我想用我的查询输出填充它:

List<TFSquery> z = (from msg in _DB.Msg 
                    select new { msg.MsgUID, msg.CreateStamp }).ToList();

Then would I loop the output into my List so that I can then output in my Json return string? 那么我会将输出循环到我的List中,以便我可以在我的Json返回字符串中输出吗? And when I use a LIST VS IENUMERABLE VS IQUERYABLE ?? 当我使用LIST VS IENUMERABLE VS IQUERYABLE

return Json(new { Result = z }, JsonRequestBehavior.AllowGet);     

My rules of thumb: 我的经验法则:

  • Use a List when you have to add, remove, or refer to an item by index. 必须按索引添加,删除或引用项目时使用列表。

  • Use a IQueryable when you have to run ad-hoc queries against it. 必须针对它运行即席查询时,请使用IQueryable

  • Use IEnumerable by default. 默认情况下使用IEnumerable

It looks like you're already doing the query "in" your database, so I'd suggest using the simplest version: IEnumerable to simply be able to loop through the results. 看起来你已经在你的数据库中“查询”,所以我建议使用最简单的版本: IEnumerable只是能够遍历结果。

If your new to .NET and C# I'd spend some time researching and becoming knowledgeable about what the different collection types are, how they differ, and when to use them. 如果您是.NET和C#的新手,我会花一些时间研究并了解不同的集合类型是什么,它们有何不同,以及何时使用它们。 You'll use collections so often it you cannot afford to have a "simple one liner" summary understanding like the other answerers posted. 你会经常使用收藏品,你不能像其他回答者那样有一个“简单的单行”概要理解。

Here is a good guide on .NET collection types: http://msdn.microsoft.com/en-us/library/0ytkdh4s.aspx 以下是.NET集合类型的一个很好的指南: http//msdn.microsoft.com/en-us/library/0ytkdh4s.aspx

IQueryable is its own special beast and deserves its own guide: http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx IQueryable是它自己的特殊野兽,值得拥有自己的指南: http//msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx

Each interface has its own set of uses. 每个接口都有自己的一组用途。

IQueryable is for deferred queries (that is, it saves the query but only executes it when it is enumerated) IQueryable用于延迟查询(即,它保存查询但仅在枚举时执行)

IEnumerable can be enumerated and that's it. IEnumerable可以枚举,就是这样。

IList can have items added and removed. IList可以添加和删除项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM