LinQ To DataSet

LINQ to DataSet 是LINQ to ADO.NET 的一个独立技术。使用LINQ to DataSet能够更 快更容易的查询DataSet对象中的数据。 LINQ to DataSet 功能主要通过DataRowExtensions和DataTableExtensions静态类 中的扩展方法来实现。LINQ to DataSet 不但能够对DataSet 对象中的单个表进行查询,而且还能够通过联接操作对DataSet对象中的多个表进行查询。

DataTableExtensions类    对表操作

DataTableExtensions类是一个静态类,它定义了DataTable类的扩展方法,主要用来操作DataTable类的实例中的数据。 DataTableExtensions类为DataTable类提供了3个扩展方法,具体如下:

AsDataView()          把DataTable 对象转成视图对象,用作数据源

AsEnumerable()       把DataTable 对象转成IEnumerable<T>对象,用作LinQ查询语句

CopyToDataTable()    把IEnumerable<T>对象转成DataTable对象

DataRowExtensions类      对行操作

DataRowExtensions类是一个静态类,它定义了DataRow类的扩展方法,主要用来操作DataRow类的实例中的数据。 DataRowExtensions类提供了2个扩展方法,具体如下表:

Field<T>()    访问DataRow对象中的每一个列值      

 int.Parse(p["CategoryID"].ToString())   //获取P行中的CategoryID值      先取到行中的列再转型,很麻烦

 Field<int>("CategoryID")              转型和取值一起做

SetField<decimal>("单价", 100);   设置DataRow对象中的每一个列值

数据源应该是视图类型   

//网站中   简单
DataSet ds = SqlHelper.ExecuteDataSet(@"Data Source=SEALEESEALEE;Initial Catalog=Northwind;User ID=sa;Password=123", "select * from products;select * from categories"); //查询两张表的信息
标准写法    GridView1.DataSource = ds.Tables[0].AsDataView();  //把打一张转成视图,做数据源  
GridView1.DataBind();

综合:

 DataSet ds = SqlHelper.ExecuteDataSet(@"Data Source=SEALEESEALEE;Initial Catalog=Northwind;User ID=sa;Password=123",
            "select * from products;select * from categories"); //查询两张表的信息
        DataTable products = ds.Tables[0]; //第一张表
        DataTable category = ds.Tables[1]; //第二张表
        //联合查询  价格小于10的
        var temp = from p in products.AsEnumerable() //转型   //p就是products表中的行
                   join c in category.AsEnumerable() on p.Field<int>("CategoryID") equals c.Field<int>("CategoryID")  //p["CategoryID"] equals c["CategoryID"]
                   where p.Field<decimal>("unitprice") < 10
                   select new
                   {
                       productName = p.Field<string>("ProductName"),//p["ProductName"],   //取值
                       categoryName = c.Field<string>("CategoryName"),//c["CategoryName"]
                       price = p.Field<decimal>("unitprice")

                   };
        //手动打造一张表
        DataTable dt = new DataTable();
        //确定有什么列
        dt.Columns.Add("产品名");
        dt.Columns.Add("分类名");
        dt.Columns.Add("单价");
        foreach (var item in temp)
        {
            //为每一行加载数据
            DataRow row = dt.NewRow();   //不能用new DataRow   这里应该是在dt中添加行
            row[0] = item.productName;   //第一列的数据
            row[1] = item.categoryName;
            row[2] = item.price;
            dt.Rows.Add(row);         //添加行
        }
        GridView1.DataSource = dt.AsDataView();    //把表转成视图做数据源
        GridView1.DataBind();
原文地址:https://www.cnblogs.com/Sea1ee/p/5944011.html