LinQ高级查询、组合查询、IQueryable集合类型

LinQ高级查询:

1、模糊查询(包含)

Repeater1.DataSource = con.car.Where(r =>r.name.Contains(s)).ToList();

2、开头

Repeater1.DataSource = con.car.Where(r =>r.name.StartsWith(s)).ToList();

3、结尾

Repeater1.DataSource = con.car.Where(r =>r.name.EndsWith(s)).ToList();

4、个数

IEnumerable<car> clist = con.car;
int count =clist.Count;

5、最大最小值平均值

con.car.Max(r => r.price);
con.car.Min(r => r.price);
con.car.Average(r => r.price);

6、求和、升序、降序

con.car.Sum(r => r.price);
Repeater1.DataSource = con.car.OrderBy(r => r.price);
Repeater1.DataSource = con.car.OrderByDescending(r => r.price);

7、分页

  集合的Skip方法:跳过多少条数据

  Take方法:取前多少条数据  

  例:打开页面绑定第一页的数据

int count = 4;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            using (Data0928DataContext con = new Data0928DataContext())
            {
                Repeater1.DataSource = con.Users.Take(count).ToList();
                Repeater1.DataBind();
            }
        }
    }

8、组合查询

  首先介绍一下IQueryable集合,在LinQ中使用此集合,不会立马查询出实际的数据,而是在真正使用到此集合时才会去执行查询,可以提高服务器内存的效率,避免占用内存过多导致服务器崩溃,但需注意如果中途把此集合ToList()则会立刻执行并返回实际的数据。

using (Data0928DataContext con = new Data0928DataContext())
        {
            IQueryable<Users> ulist = con.Users;
            if (name.Length > 0)
            {
                ulist = ulist.Where(r => r.UserName.Contains(name));
            }
            if (nick.Length > 0)
            {
                ulist = ulist.Where(r => r.NickName.Contains(nick));
            }
            if (year.Length > 0)
            {
                ulist = ulist.Where(r => Convert.ToDateTime(r.Birthday).Year.ToString() == year);
            }
            Repeater1.DataSource = ulist.Take(count);
            Repeater1.DataBind();
        }    

9、集合的交集

  集合的Intersect方法,取两个集合的交集

var allList = nameList.Intersect(brandList);

另:

  并集:Union方法

  差集:Except方法

posted @ 2017-02-09 16:07  苏迁时  阅读(3336)  评论(0编辑  收藏  举报