65.9K
CodeProject 正在变化。 阅读更多。
Home

在 DataSet 上使用 LINQ 技术实现简单的 SQL Group by 功能

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2投票s)

2008年7月26日

CPOL

2分钟阅读

viewsIcon

61483

downloadIcon

433

使用 LINQ 实现简单的 SQL group by 功能。

引言

在本文中,我将解释使用 LINQ 技术在数据集对象上实现 group by 功能。

什么是 LINQ

LINQ 代表“语言集成查询”。 这是 Microsoft .NET Framework 组件,它使用类似于 SQL 的语法为 .NET 语言 添加了本机数据查询功能。 通过使用基本的查询表达式和模式,我们可以查询和转换来自任何支持 LINQ 的数据源的数据,例如 ADO.NET 数据集、XML 文档和流以及 .NET 集合。

在使用 LINQ 时,需要以下三个步骤

  1. 创建数据源;这些将用于 LINQ 表达式。
  2. 创建 LINQ 表达式。
  3. 执行查询表达式以获取查询的结果。

示例代码

在这个示例项目中,我通过使用类文件 clsDB 完成了第一步,即创建数据源。 在这个类中,我创建了两个数据表 CustomerOrders,并在其中插入了一些示例记录。 clsDB 类的构造函数返回一个 DataSet 对象,该对象保存这些示例数据表。

/// <summary>
/// STEP 1 :  In the page load event, we are initializing the clsDB class object.
/// ClsDB class creates and inserts the data into two data tables Customer 
/// and Orders. By using the MyDataSet public property of clsDB, we can access  
/// these two tables.
/// In brief, with the clsdb object I have created a DataSet with two tables.
///           
/// STEP 2:   Bind the DataSet to the Data Grid. 
/// 
/// NOTE : I have used the clsDB class to create and fill a dataset in memory 
/// to avoid DB connections.  
/// Instead of this, you can write the standard SQL connection 
/// code to get the data and fill the dataset from back end.
/// 
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>

protected void Page_Load(objectsender, EventArgs e)
{
    lblCaption.Text = "Orders Table <BR> With out using LINQ";
 
    if(!IsPostBack)
    {
        //STEP 1:
        objClsDB = newClsDB();
        Session["DBObject"]= objClsDB;

        //STEP 2:
        DtGrid.DataSource =objClsDB.MyDataSet.Tables["Orders"];
        DtGrid.DataBind();
    }
    else
    {
        objClsDB = (ClsDB)Session["DBObject"];
    }
}

第二步是编写查询表达式

什么是查询表达式

查询表达式是以查询语法表示的查询。

查询表达式必须以“from”子句开头,以“select”或“group”子句结尾。
在这个示例项目中,我创建了四种不同类型的查询表达式。
其中之一是:通过分组 customerId 来显示 order 表中的所有记录。

/// Simple SQl Query : 
select [Order].* from [Order]                    
group by [Order].["CustomerID"]      

/// LINQ Example:                          
     var groupbyfilter= from dr in  objClsDB.MyDataSet.Tables["Order"].AsEnumerable()
                            group dr by dr["CustomerID"];

第三步是执行查询表达式

我们在第 2 步中创建的查询表达式仅包含查询。它不包含查询的结果。要获得结果,我们应该执行它。

在这个例子中,查询表达式变量“groupbyfilter”不包含查询的结果。为了获得结果,我们应该执行查询。在这里,我针对 foreach 循环执行了查询表达式变量,并将结果复制到一个表中。

查询变量在通过 foreach 循环或 IEnumerable.movenext() 迭代时,应该始终生成一系列元素。

foreach(var x in groupbyfilter)
      x.CopyToDataTable(dt, LoadOption.OverwriteChanges);

此项目中使用的查询表达式

“Group by”按钮功能

通过分组 order 表中的 CustomerId,显示 Order 表中的所有记录。

protected void btnGroupby_Click(object sender, EventArgs e)
    {
        // Step 1: Create LINQ Query Expression: 
        var groupbyfilter = from dr in objClsDB.MyDataSet.Tables["Order"].AsEnumerable()
                            group dr by dr["CustomerID"] ;
         DataTable dt=objClsDB.MyDataSet.Tables["Order"].Clone();

        // Step 2:Execute the Query and store the results into temp table
        foreach(var x in groupbyfilter)
            x.CopyToDataTable(dt, LoadOption.OverwriteChanges);
        
        //Step 3: Temp tables is binded to the DatsGrid. To display the query results.
        DtGrid.DataSource = dt;
        DtGrid.DataBind();
 }

“Group by Having”按钮功能

它提供来自 Order 表的记录,这些记录每个 customer 都有超过 4 个销售 order

protected void btnGroupbyhaving_Click(object sender, EventArgs e)
    {
        // Step 1: Define the Query Expression 
        var groupbyhaving = from dr in objClsDB.MyDataSet.Tables["Order"].AsEnumerable()
                           group dr by
                           dr["CustomerID"] into newdr
                           where newdr.Count() > 4
                           select newdr;
  
        DataTable dt = objClsDB.MyDataSet.Tables["Order"].Clone();

        // Step 2: Execute the Query and store the results into temp table
        foreach (var x in groupbyhaving)
           x.CopyToDataTable(dt, LoadOption.OverwriteChanges);

        // Step 3 : Temp tables is binded to the DataGrid. To display the query results.
           DtGrid.DataSource = dt;
           DtGrid.DataBind();
    }

“OrderBy”按钮功能

基于 BillDate 的排序,显示 Order 表中的所有记录

protected void btnOrderby_Click(object sender, EventArgs e)
{
    // Step 1: Define the Query Expression 
    var orderByDate = from dr in objClsDB.MyDataSet.Tables["Order"].AsEnumerable()
                      orderby dr["BillDate"]  ascending
                      select dr;
 
    DataTable dt = objClsDB.MyDataSet.Tables["Order"].Clone();
 
    // Step 2: Execute the Query and store the results into temp table 
    foreach (var x in orderByDate)
        dt.Rows.Add(dt.NewRow().ItemArray =x.ItemArray);
 
    // Step 3 : Temp tables is binded to the DataGrid. To display the query results.
    DtGrid.DataSource = dt;
    DtGrid.DataBind();
}

“采购订单详情”按钮功能

列出客户姓名及其总购买金额。 在这里,LINQ 应用于多个表。

protected void btnPurchaseDet_Click(object sender, EventArgs e)
    {
       // Step 1: Define the Query Expression 
       var groupbyhaving = from dr in objClsDB.MyDataSet.Tables["Order"].AsEnumerable()
                           group dr by dr["CustomerID"] into newdr
                           select new
                           {
                                GrandTotal= newdr.Sum(
                      tempRec => Convert.ToDouble(tempRec["BillAmount"])) ,
                           CustomerName =
                           from dr2 in objClsDB.MyDataSet.Tables
			["Customer"].AsEnumerable()
                  where Convert.ToInt32(dr2["CustomerID"]) == Convert.ToInt32(newdr.Key) 
                     select dr2["CustomerName"]
                           };

        List<result> resultCollection = new List<result>();
 
        // Step 2: Execute the Query and store the results into List Collection 
        foreach(var x in groupbyhaving)
        {
            resultCollection.Add(new result {
                CustomerName = x.CustomerName.First().ToString(),
				Amount = x.GrandTotal });
        }

        // Step 3 : Temp tables is binded to the DataGrid. To display the query results.
        DtGrid.DataSource = resultCollection;
        DtGrid.DataBind();
}

历史

  • 2008 年 7 月 26 日:初始发布
© . All rights reserved.