LINQ - 数据集

LINQ - 数据集 首页 / LinQ入门教程 / LINQ - 数据集

数据集在内存中提供了极为有用的数据表示形式,并用于各种基于数据的应用程序。 LINQ to Dataset是LINQ to ADO.NET的技术之一,它有助于轻松地对Dataset的数据执行查询,并提高了生产率。

LINQ数据集

LINQ to Dataset使开发人员的查询任务变得简单,他们不需要用特定的查询语言编写查询,而是可以用编程语言编写查询, LINQ to Dataset也可用于查询从多个数据源合并数据的位置,就像LINQ to SQL和LINQ to XML一样,它也不需要任何LINQ提供程序来访问内存集合中的数据。

以下是LINQ to Dataset查询的简单示例,其中首先获取数据源,然后用两个数据表填充数据集。在两个表之间创建关系,并通过join子句针对两个表创建LINQ查询。最后,使用foreach循环显示所需的输出。

C#

无涯教程网

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LINQtoDataset {
   class Program {
      static void Main(string[] args) {
      
         string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();

         string sqlSelect = "SELECT * FROM Department;" + "SELECT * FROM Employee;";

         //创建数据适配器以从数据库中检索数据
         SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);
        
         //创建表映射
         da.TableMappings.Add("Table", "Department");
         da.TableMappings.Add("Table1", "Employee");

         //创建并填充数据集
         DataSet ds = new DataSet();
         da.Fill(ds);

         DataRelation dr = ds.Relations.Add("FK_Employee_Department",
                           ds.Tables["Department"].Columns["DepartmentId"],
                           ds.Tables["Employee"].Columns["DepartmentId"]);

         DataTable department = ds.Tables["Department"];
         DataTable employee = ds.Tables["Employee"];

         var query = from d in department.AsEnumerable()
                     join e in employee.AsEnumerable()
                     on d.Field<int>("DepartmentId") equals
                     e.Field<int>("DepartmentId")                        
                     select new {
                        EmployeeId = e.Field<int>("EmployeeId"),
                        Name = e.Field<string>("Name"),                            
                        DepartmentId = d.Field<int>("DepartmentId"),                            
                        DepartmentName = d.Field<string>("Name")
                     };

         foreach (var q in query) {
            Console.WriteLine("Employee Id={0} , Name={1} , Department Name={2}",
               q.EmployeeId, q.Name, q.DepartmentName);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

链接:https://www.learnfk.comhttps://www.learnfk.com/linq/linq-dataset.html

来源:LearnFk无涯教程网

Imports System.Data.SqlClient
Imports System.Linq

Module LinqToDataSet

   Sub Main()
   
      Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString()

      Dim sqlSelect As String = "SELECT * FROM Department;" + "SELECT * FROM Employee;"
      Dim sqlCnn As SqlConnection = New SqlConnection(connectString)
      sqlCnn.Open()

      Dim da As New SqlDataAdapter
      da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)

      da.TableMappings.Add("Table", "Department")
      da.TableMappings.Add("Table1", "Employee")

      Dim ds As New DataSet()
      da.Fill(ds)

      Dim dr As DataRelation = ds.Relations.Add("FK_Employee_Department", ds.Tables("Department").Columns("DepartmentId"), ds.Tables("Employee").Columns("DepartmentId"))

      Dim department As DataTable = ds.Tables("Department")
      Dim employee As DataTable = ds.Tables("Employee")

      Dim query = From d In department.AsEnumerable()
                  Join e In employee.AsEnumerable() On d.Field(Of Integer)("DepartmentId") Equals
                  e.Field(Of Integer)("DepartmentId")
                  Select New Person With { _
                        .EmployeeId = e.Field(Of Integer)("EmployeeId"),
                        .EmployeeName = e.Field(Of String)("Name"),
                        .DepartmentId = d.Field(Of Integer)("DepartmentId"),
                        .DepartmentName = d.Field(Of String)("Name")
                  }

      For Each e In query
         Console.WriteLine("Employee Id={0} , Name={1} , Department Name={2}", e.EmployeeId, e.EmployeeName, e.DepartmentName)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub
  
   Class Person
      Public Property EmployeeId As Integer
      Public Property EmployeeName As String
      Public Property DepartmentId As Integer
      Public Property DepartmentName As String
   End Class
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

Employee Id=1, Name=William, Department Name=Account
Employee Id=2, Name=Benjamin, Department Name=Account
Employee Id=3, Name=Miley, Department Name=Sales

Press any key to continue.

查询数据集

在开始使用LINQ to Dataset查询数据集之前,将数据加载到Dataset是至关重要的,这可以通过使用DataAdapter类或LINQ to SQL来完成。使用LINQ to Dataset进行查询的方式与将LINQ与其他启用LINQ的数据源一起使用来进行查询的方式非常相似。

在以下单表查询中,将从SalesOrderHeaderTtable收集所有在线订单,然后将订单ID,订单日期以及订单号显示为输出。

C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinqToDataset {
   class SingleTable {
      static void Main(string[] args) {
      
         string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();

         string sqlSelect = "SELECT * FROM Department;";

         //创建数据适配器以从数据库中查询数据
         SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connectString);

         //创建表映射
         da.TableMappings.Add("Table", "Department");           

         //创建并填充数据集
         DataSet ds = new DataSet();
         da.Fill(ds);

         DataTable department = ds.Tables["Department"];            

         var query = from d in department.AsEnumerable()                        
         select new {
            DepartmentId = d.Field<int>("DepartmentId"),
            DepartmentName = d.Field<string>("Name")
         };

         foreach (var q in query) {
            Console.WriteLine("Department Id={0} , Name={1}",
               q.DepartmentId, q.DepartmentName);
         }

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Imports System.Data.SqlClient
Imports System.Linq

Module LinqToDataSet

   Sub Main()
   
      Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString()

      Dim sqlSelect As String = "SELECT * FROM Department;"
      Dim sqlCnn As SqlConnection = New SqlConnection(connectString)
      sqlCnn.Open()

      Dim da As New SqlDataAdapter
      da.SelectCommand = New SqlCommand(sqlSelect, sqlCnn)

      da.TableMappings.Add("Table", "Department")
      Dim ds As New DataSet()
      da.Fill(ds)

      Dim department As DataTable = ds.Tables("Department")

      Dim query = From d In department.AsEnumerable()
      Select New DepartmentDetail With {
         .DepartmentId = d.Field(Of Integer)("DepartmentId"),
            .DepartmentName = d.Field(Of String)("Name")
      }

      For Each e In query
         Console.WriteLine("Department Id={0} , Name={1}", e.DepartmentId, e.DepartmentName)
      Next

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
   End Sub

   Public Class DepartmentDetail
      Public Property DepartmentId As Integer
      Public Property DepartmentName As String
   End Class
   
End Module

编译并执行以上C#或VB的代码时,将产生以下输出-

Department Id=1, Name=Account
Department Id=2, Name=Sales
Department Id=3, Name=Pre-Sales
Department Id=4, Name=Marketing

Press any key to continue.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Python -〔尹会生〕

Go语言核心36讲 -〔郝林〕

如何做好一场技术演讲 -〔极客时间〕

玩转webpack -〔程柳锋〕

编辑训练营 -〔总编室〕

研发效率破局之道 -〔葛俊〕

流程型组织15讲 -〔蒋伟良〕

高并发系统实战课 -〔徐长龙〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)