Linq ToList()方法 [英] Linq ToList() method

查看:91
本文介绍了Linq ToList()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们在LINQ select查询结束时使用.ToList()方法?任何人都可以解释它的好处,如果不使用ToList()方法,那么可能出现什么问题?

Why we use .ToList() method at the end of the LINQ select query? Can anyone explain its benefit and if do''t use ToList() method then what problem may arise?

推荐答案

如果你不使用 .ToList没问题()的。它不是必须使用 .ToList()。如果你想将结果存储到List对象中,它只是强制性的。

否则你可以使用''var''关键字代替 .ToList()如果你只是想枚举。



注意:使用''var'' comiler会自动从右侧表达式推断出返回类型。您可以将 鼠标悬停在''var'' 上,它会显示确切类型。



我希望你明白了。
No issues if you dont use .ToList(). Its not compulsory to use .ToList(). Its only mandatory if you want to store the result into a List object.
Otherwise you can use ''var'' keyword instead of .ToList() if you just simply want to enumerate.

Note: Using ''var'' the comiler will automatically infer the return type from right side expression. You can hover your mouse on ''var'' it shows you the exact type.

I hope you understand.


仅在需要数据时执行Linq查询。这样做的好处是可以将单个查询分散到多个查询中,而不会降低性能。当我们调用ToList()时,执行查询并将数据检索到新的List< type>中。在不调用ToList()的情况下,它只是一个在需要数据时会执行的查询。现在,想想你正在使用Linq to SQL DataContext的情况。您可以创建数据上下文并构建查询。现在,您处理数据上下文,然后尝试使用查询。在处理数据上下文时,查询将失败并引发异常。现在,比如说,在处理数据上下文之前,通过调用ToList()将数据存储在List变量中。然后将检索数据,您可以使用该列表。因此,如果您在任何时候认为基础数据可能会在使用数据时发生变化或无法使用,您可以调用ToList()并保留List供以后使用。


当您的查询可以返回多于1个结果时,使用ToList()方法,以便您可以遍历结果。如果您的查询只返回1个结果,则不必使用ToList()。



The ToList() method is used when your query can return more then 1 result, so that you can iterate through the results. If your query returns just 1 result you don''t have to use ToList().

// select item with given id
// query returns 1 result, you can catch it in a single object model.
ItemModel item = db.Items.Find(id);

// select all items
// query returns more then 1 result, you have to parse it to a List.
List<ItemModel> items = db.Items.ToList();


这篇关于Linq ToList()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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