查询类型化数据集Query typed DataSets

如果在应用程序设计DataSet时已知的架构,则建议在使用 LINQ to DataSet 时使用类型化DataSetIf the schema of the DataSet is known at application design time, we recommend that you use a typed DataSet when using LINQ to DataSet. 类型化 DataSet 是从 DataSet 中派生的类。A typed DataSet is a class that derives from a DataSet. 因此,它继承 DataSet 的所有方法、事件和属性。As such, it inherits all the methods, events, and properties of a DataSet. 此外,类型化 DataSet 还提供强类型方法、事件和属性。Additionally, a typed DataSet provides strongly typed methods, events, and properties. 这意味着可以按名称而不使用基于集合的方法来访问表和列。This means that you can access tables and columns by name, instead of using collection-based methods. 这可使查询更简单、更具可读性。This makes queries simpler and more readable. 有关详细信息,请参阅类型化数据集For more information, see Typed DataSets.

LINQ to DataSet 还支持对类型化DataSet进行查询。LINQ to DataSet also supports querying over a typed DataSet. 对于类型化 DataSet,您不必使用泛型 Field 方法或 SetField 方法即可访问列数据。With a typed DataSet, you do not have to use the generic Field method or SetField method to access column data. 由于 DataSet 中包括类型信息,因此属性名称在编译时可用。Property names are available at compile time because the type information is included in the DataSet. LINQ to DataSet 提供作为正确类型的列值的访问,以便在编译代码而不是在运行时捕获类型不匹配错误。LINQ to DataSet provides access to column values as the correct type, so that type mismatch errors are caught when the code is compiled instead of at run time.

必须先使用 Visual Studio 中的DataSet数据集设计器生成类,然后才能开始查询类型化的。Before you can begin querying a typed DataSet, you must generate the class by using the DataSet Designer in Visual Studio. 有关详细信息,请参阅创建和配置数据集For more information, see Create and configure DataSets.

示例Example

下面的示例演示对类型化 DataSet 进行查询:The following example shows a query over a typed DataSet:

var query = from o in orders
            where o.OnlineOrderFlag == true
            select new { o.SalesOrderID,
                         o.OrderDate,
                         o.SalesOrderNumber };

foreach(var order in query)
{
    Console.WriteLine("{0}\t{1:d}\t{2}",
      order.SalesOrderID,
      order.OrderDate,
      order.SalesOrderNumber);
}
Dim orders = ds.Tables("SalesOrderHeader")

Dim query = _
       From o In orders _
       Where o.OnlineOrderFlag = True _
       Select New {SalesOrderID := o.SalesOrderID, _
                   OrderDate := o.OrderDate, _
                   SalesOrderNumber := o.SalesOrderNumber}

For Each Dim onlineOrder In query
 Console.WriteLine("{0}\t{1:d}\t{2}", _
 onlineOrder.SalesOrderID, _
 onlineOrder.OrderDate, _
 onlineOrder.SalesOrderNumber)
Next

请参阅See also