Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

adapter = new SqlDataAdapter(comm);

adapter.Fill(ds);

The three tables loaded onto the DataSet can now be referenced using three DataTableobjects:

DataTable customersTable = ds.Tables[0]; //---Customers---

DataTable ordersTable = ds.Tables[1]; //---Orders---

DataTable orderDetailsTable = ds.Tables[2]; //---Order Details---

The following LINQ query joins two DataTable objects — customersTableand ordersTable— using the query syntax:

//---using query syntax to join two tables - Customers and Orders-

var query1 =

(from customer in customersTable.AsEnumerable()

join order in ordersTable.AsEnumerable() on

customer.Field("CustomerID") equals order.Field("CustomerID")

select new {

id = customer.Field("CustomerID"),

CompanyName = customer.Field("CompanyName"),

ContactName = customer.Field("ContactName"),

OrderDate = order.Field("OrderDate"),

ShipCountry = order.Field("ShipCountry")

}).ToList();

As evident in the query, the Customersand Orderstable are joined using the CustomerIDfield. The result is reshaped using an anonymous type and then converted to a List object using the ToList()extension method. You can now bind the result to a DataGridViewcontrol if desired. Figure 14-8 shows the result bound to a DataGridViewcontrol.

Figure 148 You can also rewrite the query using the method syntax - фото 197

Figure 14-8

You can also rewrite the query using the method syntax:

//---using method syntax to join two tables - Customers and Orders

var query1 =

(customersTable.AsEnumerable().Join(ordersTable.AsEnumerable(),

customer => customer.Field("CustomerID"),

order => order.Field("CustomerID"),

(customer, order) => new {

id = customer.Field("CustomerID"),

CompanyName = customer.Field("CompanyName"),

ContactName = customer.Field("ContactName"),

OrderDate = order.Field("OrderDate"),

ShipCountry = order.Field("ShipCountry")

})).ToList();

The following query joins three DataTable objects — customersTable, ordersTable, and orderDetailsTable— and sorts the result according to the OrderIDfield:

//---three tables join---

var query2 =

(from customer in customersTable.AsEnumerable()

join order in ordersTable.AsEnumerable() on

customer.Field("CustomerID") equals order.Field("CustomerID")

join orderDetail in orderDetailsTable.AsEnumerable() on

order.Field("OrderID") equals orderDetail.Field("OrderID")

orderby order.Field("OrderID")

select new {

id = customer.Field("CustomerID"),

CompanyName = customer.Field("CompanyName"),

ContactName = customer.Field("ContactName"),

OrderDate = order.Field("OrderDate"),

ShipCountry = order.Field("ShipCountry"),

OrderID = orderDetail.Field("OrderID"),

ProductID = orderDetail.Field("ProductID")

}).ToList();

As evident from the query, the Customerstable is related to the Orderstable via the CustomerIDfield, and the Orderstable is related to the Order Detailstable via the OrderIDfield.

Figure 14-9 shows the result of the query.

Figure 149 Typed DataSet So far youve used the Fieldextension method - фото 198

Figure 14-9

Typed DataSet

So far you've used the Field()extension method to access the field of a DataTableobject. For example, the following program uses LINQ to DataSet to query all the customers living in the USA. The result is then reshaped using an anonymous type:

SqlConnection conn;

SqlCommand comm;

SqlDataAdapter adapter;

DataSet ds = new DataSet();

conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;" +

"Initial Catalog=Northwind;Integrated Security=True");

comm = new SqlCommand("SELECT * FROM Customers", conn);

adapter = new SqlDataAdapter(comm);

adapter.Fill(ds, "Customers");

var query1 =

(from customer in ds.Tables[0].AsEnumerable()

where customer.Field("Country") == "USA"

select new {

CustomerID = customer.Field("CustomerID"),

CompanyName = customer.Field("CompanyName"),

ContactName = customer.Field("ContactName"),

ContactTitle = customer.Field("ContactTitle")

}).ToList();

dataGridView1.DataSource = query1;

As your query gets more complex, the use of the Field()extension method makes the query unwieldy. A good way to resolve this is to use the typed DataSet feature in ADO.NET. A typed DataSet provides strongly typed methods, events, and properties and so this means you can access tables and columns by name, instead of using collection-based methods.

To add a typed DataSet to your project, first add a DataSetitem to your project in Visual Studio 2008 (see Figure 14-10). Name it TypedCustomersDataset.xsd.

Figure 1410 In the Server Explorer window open a connection to the database - фото 199

Figure 14-10

In the Server Explorer window, open a connection to the database you want to use (in this case it is the Northwind database) and drag and drop the Customerstable onto the design surface of TypedCustomersDataSet.xsd(see Figure 14-11). Save the TypedCustomersDataSet.xsdfile.

Figure 1411 With the typed DataSet created rewrite the query as follows - фото 200

Figure 14-11

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x