LINQ: difference between Single(), First(), and Take(1)

来源:互联网 发布:苹果手机屏幕录像软件 编辑:程序博客网 时间:2024/06/08 19:21

LINQ provides a few different methods that return you a single object: Single(), First(), and Take(1).It took me a while, but I think I understand the difference: Single() operates on a collection of exactly one object and simply returns the object. First() operates on a collection of any number of objects and returns the first object. Take(1) operates on a collection of any number of objects and returns a collection containing the first object....

Linq提供了一些不同的返回单个对象的函数:Single(),First()和Take(1)。

Single():操作一个集合,同时强要求只有一个对象匹配,并返回这一个。

First():操作一个集合,可以有多个对象匹配,但是只返回第一个。

Take(1):操作一个集合,可以有对个对象匹配,单只返回第一个,但是这里返回的是一个集合,而不是单个的概念。



GridView1.DataSource = dataContext.Customers.Where(p => p.City.Length > 2 && p.CompanyName.Length > 5).First();
我想将查询出来的第一条数据绑定到GridView上,这样写不对,因为获得不了相关接口。请问该如何在一句内实现绑定?

GridView1.DataSource = dataContext.Customers.Where(p => p.City.Length > 2 && p.CompanyName.Length > 5).Take(1);

原创粉丝点击