LINQ与ADO.NET:DataTable/DateSet的使用

1.简介

    对于ADO.NET早期开发人员来说,使用DataTable和DataSet访问数据库是家常便饭的事,但LINQ真的是太方便了,它可以取代像DataTable.Select()这类效率不高的查询语句,也可以处理使用DataSet/DataTable现有方法无法实现的查询需求。

    在LINQ推出后,微软扩展了DataTable类型,加入了与LINQ的IEnumerable<T>有关的方法AsEnumerable(),通过这个方法可以获取IEnumerable<DataRow>集合,然后就能以一般的LINQ访问方式来查询IEnumerable<DataRow>了。不管是检索、排序还是统计,都不再需要使用Select()和Compute()方法来实现了。CopyToDataTable<T>()则是将LINQ的查询结果转换成另一个DataTable。

2.例子

//Fill the DataSet
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture();
FillDataSet(ds);

DataTable orders = ds.Tables["SalesOrderHeader"];

//Query the SalesOrderHeader table for orders placed
//after August 8,2016.
IEnumerable<DataRow> query = 
	from order in orders.AsEnumerable()
	where order.Field<DateTime>("OrderDate") > new DateTime(2016,8,1)
	select order;
	
//Create a table from the query
DataTable boundTable = query.CopyToDataTable<DataRow>();

//Bind the table to a System.Windows.Forms.BindingSource object
//which acts as a proxy for a System.Windows.Forms.DataGridView object
bindingSource.DataSource = boundTable;

    下面介绍DataRow本身,在一开始时DataRow基本上是提供松散类型的数据容器,因此在处理查询时都要先转换才能查询。LINQ推出后,强化了DataRow强类型功能,以作为查询时简化类型转换之用,它们分别是Field<T>()以及SetField<T>()两个方法,这两个都是重载方法,可根据需要来调用。例如:

DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable products = ds.Tables["Product"];

var query = 
	from product in products.AsEnumerable()
	where product.Field<string>("Color") == "Red"
	select new
	{
		Name = product.Field<string>("Name"),
		ProductNumber = product.Field<string>("ProductNumber"),
		ListPrice = product.Field<Decimal>("ListPrice")
	};

foreach(var product in query)
{
	Console.WriteLine("Name:{0}",product.Name);
	Console.WriteLine("Product number:{0}",product.ProductNumber);
	Console.WriteLine("List price:${0}",product.ListPrice);
	Console.WriteLine("");
}

    除了以强类型访问DataRow的字段外,微软也提供了强类型比较的DataRowComparer类,以处理当使用强类型方式查询DataRow时所需要的类型转换处理工作。

var contacts = contacts1.AsEnumerable().Intersect(
	contacts2.AsEnumerable(),DataRowComparer.Default);

猜你喜欢

转载自blog.csdn.net/cgs_______/article/details/80430198