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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

To make use of LINQ to DataSet, ensure that you have a reference to System.Data.DataSetExtensions.dllin your project.

To display the result, you can either bind the result to a DataGridView control using the AsDataView()method:

//---bind to a datagridview control---

dataGridView1.DataSource = authors.AsDataView();

Or, iteratively loop through the result using a foreach loop:

foreach (DataRow row in authors) {

Console.WriteLine("{0} - {1}, {2}",

row["au_id"], row["au_fname"], row["au_lname"]);

}

To query the authors based on their contract status, use the following query:

EnumerableRowCollection authors =

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

where author.Field("Contract") == true

select author;

Reshaping Data

Using the new anonymous types feature in C# 3.0, you can define a new type without needing to define a new class. Consider the following statement:

//---query for authors living in CA---

var authors =

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

where author.Field("State") == "CA"

select new {

ID = author.Field("au_id"),

FirstName = author.Field("au_fname"),

LastName = author.Field("au_lname")

};

Here, you select all the authors living in the CA state and at the same time create a new type consisting of three properties: ID, FirstName, and LastName. If you now type the word authors, IntelliSense will show you that authors is of type EnumerableRowCollection<'a> authors, and 'ais an anonymous type containing the three fields (see Figure 14-6).

Figure 146 You can now print out the result using a foreach loop foreach - фото 195

Figure 14-6

You can now print out the result using a foreach loop:

foreach (var row in authors) {

Console.WriteLine("{0} - {1}, {2}",

row.ID, row.FirstName, row.LastName);

}

To databind to a DataGridView control, you first must convert the result of the query to a List object:

//---query for authors living in CA---

var authors =

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

where author.Field("State") == "CA"

select new {

ID = author.Field("au_id"),

FirstName = author.Field("au_fname"),

LastName = author.Field("au_lname")

}).ToList();

//---bind to a datagridview control---

dataGridView1.DataSource = authors;

Aggregate Functions

In an earlier section, you used the following query to obtain a list of authors living in CA:

var authors =

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

where author.Field("State") == "CA"

select author;

To get the total number of authors living in CA, you can use the Count()extension method (also known as an aggregate function), like this:

Console.WriteLine(authors.Count());

A much more efficient way would be to use the following query in method syntax:

var query =

ds.Tables[0].AsEnumerable().Count(a => a.Field("State")=="CA");

Console.WriteLine(query);

LINQ supports the following standard aggregate functions:

Aggregate function Description
Aggregate Performs a custom aggregation operation on the values of a collection.
Average Calculates the average value of a collection of values.
Count Counts the elements in a collection, optionally only those elements that satisfy a predicate function.
LongCount Counts the elements in a large collection, optionally only those elements that satisfy a predicate function.
Max Determines the maximum value in a collection.
Min Determines the minimum value in a collection.
Sum Calculates the sum of the values in a collection.

For example, the following statements print out the largest odd number contained in the numsarray:

int[] nums = {

12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32

};

var maxOddNums = nums.Where

(n => n % 2 == 1).OrderByDescending(n => n).Max();

Console.WriteLine("Largest odd number: {0}", maxOddNums); //---87---

The following statements print out the sum of all the odd numbers in nums:

int[] nums = {

12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32

};

var sumOfOddNums = nums.Where

(n => n % 2 == 1).OrderByDescending(n => n).Sum();

Console.WriteLine("Sum of all odd number: {0}", sumOfOddNums); //---197---

Joining Tables

So far you've been dealing with a single table. In real life, you often have multiple, related tables. A good example is the Northwind sample database, which contains a number of related tables, three of which are shown in Figure 14-7.

Figure 147 Here the Customerstable is related to the Orderstable via the - фото 196

Figure 14-7

Here, the Customerstable is related to the Orderstable via the CustomerIDfield, while the Orderstable is related to the Order_Detailstable via the OrderIDfield.

You can use LINQ to DataSet to join several tables stored in a DataSet. Here's how. First, load the three tables into the DataSet, using the following code:

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

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

comm =

new SqlCommand("SELECT * FROM Customers; SELECT * FROM Orders; SELECT * FROM [Order Details]",

conn);

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

Интервал:

Закладка:

Сделать

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

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


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

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

x