学习LINQ时,经常会遇到LINQ to DataSet问题,这里将介绍LINQ to DataSet问题的解决方法。
使用 LINQ to DataSet 可以更快更容易地查询在 DataSet 对象中缓存的数据。具体而言,通过使开发人员能够使用编程语言本身而不是通过使用单独的查询语言来编写查询,LINQ to DataSet 可以简化查询。对于现在可以在其查询中利用 Visual Studio 所提供的编译时语法检查、静态类型和 IntelliSense 支持的 Visual Studio 开发人员,这特别有用。
LINQ to DataSet 也可用于查询从一个或多个数据源合并的数据。这可以使许多需要灵活表示和处理数据的方案(例如查询本地聚合的数据和 Web 应用程序中的中间层缓存)能够实现。具体地说,一般报告、分析和业务智能应用程序将需要这种操作方法。
LINQ to DataSet 功能主要通过 DataRowExtensions 和 DataTableExtensions 类中的扩展方法公开。LINQ to DataSet 基于并使用现有的 ADO.NET 2.0 体系结构生成,在应用程序代码中不能替换 ADO.NET 2.0。现有的 ADO.NET 2.0 代码将继续在 LINQ to DataSet 应用程序中有效。
下面看一个例子:
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture
FillDataSet(ds);
DataTable products = ds.Tables["Product"];
var query =
from product in products.AsEnumerable()
where !product.IsNull("Color") &&
(string)product["Color"] == "Red"
select new
{
Name = product["Name"],
ProductNumber = product["ProductNumber"],
ListPrice = product["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("");
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
使用扩展之后的例子:
// Fill the DataSet.
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("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("");
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
【编辑推荐】