LinQ的高级查询

  • A+
所属分类:MVC

LinQ的高级查询

模糊查询:

//数据库 + 自定义名称 =new 数据库
//例子:
mydbDataContext con = new mydbDataContext();
//模糊查询表达式中用.Contains
con.car.Where(r=>r.name.Contains(TextBox1.Text.Trim())).ToList();
//开头查用.StartWith
con.car.Where(r => r.name.StartsWith(TextBox1.Text)).ToList();
//结尾查用.EndWith
con.car.Where(r => r.name.EndsWith(TextBox1.Text)).ToList();

最大值,最小值:

//最大值
//例子:
con.car.Max(r => r.price * r.oil).ToString();
//最小值
//例子:
con.car.Min(r => r.price).ToString();

求和,平均值:

//求和
con.car.Sum(r => r.price).ToString();
//平均值
con.car.Average(r => r.price).ToString();

升序,降序:

//升序:
con.car.OrderBy(r => r.price).ToList();
//降序:
con.car.OrderByDescending(r => r.price).ToList();

上一页,下一页,组合查询:

int PageCount = 5;//每页显示条数
//上一页,PageCount_Label.Text为当前页码
int pageNum = Convert.ToInt32(PageCount_Label.Text) - 1;
        Repeater1.DataSource = con.car.Skip((pageNum - 1) * PageCount).Take(PageCount);
        Repeater1.DataBind(); 
        PageCount_Label.Text = pageNum.ToString();
//下一页
int pageNum = Convert.ToInt32(PageCount_Label.Text) + 1;

        Repeater1.DataSource = con.car.Skip((pageNum - 1) * PageCount).Take(PageCount);
        Repeater1.DataBind();
        PageCount_Label.Text = pageNum.ToString();
//组合查询的点击事件
List list = con.car.ToList();

        if (TextBox2.Text != "")
        {
            List list1 = con.car.Where(r => r.name.Contains(TextBox2.Text)).ToList();

            list = list.Intersect(list1).ToList();
        }
        if (TextBox3.Text != "")
        {
            List list1 = con.car.Where(r => r.oil == Convert.ToDecimal(TextBox3.Text)).ToList();

            list = list.Intersect(list1).ToList();
        }
        if (TextBox4.Text != "")
        {
            List list1 = con.car.Where(r => r.powers == Convert.ToInt32(TextBox4.Text)).ToList();

            list = list.Intersect(list1).ToList();
        }
        Repeater1.DataSource = list;
        Repeater1.DataBind();
钰玺

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: