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 add items into the stack, use the Push()method. The following statements push four strings into the tasks stack:

tasks.Push("Do homework"); //---this item will be at the bottom of the stack

tasks.Push("Phone rings");

tasks.Push("Get changed");

tasks.Push("Go for movies"); //---this item will be at the top of the stack

To retrieve the elements from a stack, use either the Peek()method or the Pop()method. Peek()returns the object at the top of the stack without removing it. Pop()removes and returns the object at the top of the stack:

Console.WriteLine(tasks.Peek()); //---Go for movies---

Console.WriteLine(tasks.Pop()); //---Go for movies---

Console.WriteLine(tasks.Pop()); //---Get changed---

Console.WriteLine(tasks.Pop()); //---Phone rings---

Console.WriteLine(tasks.Pop()); //---Do homework---

If a stack is empty and you try to call the Pop()method, an InvalidOperationExceptionerror occurs. For that reason, it is useful to check the size of the stack by using the Countproperty before you perform a Pop()operation:

if (tasks.Count > 0)

Console.WriteLine(tasks.Pop());

else

Console.WriteLine("Tasks is empty");

To extract all the objects within a Stackobject without removing the elements, use a foreach statement, like this:

foreach (string t in tasks) Console.WriteLine(t);

Here's what prints out:

Go for movies

Get changed

Phone rings

Do homework

Queues

The queue is a first in, first out (FIFO) data structure. Unlike the stack, items are removed based on the sequence that they are added.

In .NET, you can use the Queue class (or the generic equivalent of Queue) to represent a queue collection. The following statement creates an instance of the Queueclass of type string:

Queue tasks = new Queue();

To add items into the queue, use the Enqueue()method. The following statement inserts four strings into the tasks queue:

tasks.Enqueue("Do homework");

tasks.Enqueue("Phone rings");

tasks.Enqueue("Get changed");

tasks.Enqueue("Go for movies");

To retrieve the elements from a queue, you can use either the Peek()method or the Dequeuedmethod. Peek()returns the object at the beginning of the queue without removing it. Dequeue()removes and returns the object at the beginning of the queue:

Console.WriteLine(tasks.Peek()); //---Do homework---

Console.WriteLine(tasks.Dequeue());-- //---Do homework---

Console.WriteLine(tasks.Dequeue());-- //---Phone rings---

Console.WriteLine(tasks.Dequeue());-- //---Get changed---

Console.WriteLine(tasks.Dequeue());-- //---Go for movies---

If a queue is empty and you try to call the Dequeue()method, an InvalidOperationExceptionerror occurs, so it is useful to check the size of the queue using the Countproperty before you perform a dequeue operation:

if (tasks.Count < 0)

Console.WriteLine(tasks.Dequeue());

else

Console.WriteLine("Tasks is empty");

To extract all the objects within a Queueobject without removing the elements, use the foreach statement, like this:

foreach (string t in tasks) Console.WriteLine(t);

Here's what prints out:

Do homework

Phone rings

Get changed

Go for movies

Summary

This chapter explained how to manipulate data using arrays. In addition, it explored the System.Collectionsnamespace, which contains the various interfaces that define basic collection functions. It also contains several useful data structures, such as a dictionary, stacks, and queues, that greatly simplify managing data in your application.

Chapter 14

Language Integrated Query (LINQ)

One of the most exciting new features in the .NET Framework v3.5 is the Language Integrated Query (LINQ). LINQ introduces to developers a standard and consistent language for querying and updating data, which include objects (such as arrays and collections), databases, XML documents, ADO.NET DataSets, and so forth.

Today, most developers need to know a myriad of technologies to successfully manipulate data. For example, if you are dealing with databases, you have to understand Structured Query Language (SQL). If you are dealing with XML documents, you must understand technologies such as XPath, XQuery, and XSLT. And if you are working with ADO.NET DataSets, then you need to know the various classes and properties in ADO.NET that you can use.

A better approach would be to have a unified view of the data, regardless of its form and structure. That is the motivation behind the design of LINQ. This chapter provides the basics of LINQ and shows how you can use LINQ to access objects, DataSets, and XML documents, as well as SQL databases.

LINQ Architecture

Figure 14-1 shows the architecture of LINQ. The bottom layer contains the various data sources with which your applications could be working. On top of the data sources are the LINQ- enabled data sources: LINQ to Objects, LINQ to DataSet, LINQ to SQL, LINQ to Entities, and LINQ to XML. LINQ-enabled data sources are also known as LINQ providers; they translate queries expressed in Visual Basic or C# into the native language of the data source. To access all these data sources through LINQ, developers use either C# or Visual Basic and write LINQ queries.

Figure 141 LINQ to Entities is beyond the scope of this book It was slated - фото 190

Figure 14-1

LINQ to Entities is beyond the scope of this book. It was slated to be released later in 2008 and is not part of Visual Studio 2008.

So how does your application view the LINQ-enabled data sources?

□ In LINQ to Objects, the source data is made visible as an IEnumerableor IQueryablecollection.

□ In LINQ to XML, the source data is made visible as an IEnumerable.

□ In LINQ to DataSet, the source data is made visible as an IEnumerable.

□ In LINQ to SQL, the source data is made visible as an IEnumerableor IQueryableof whatever custom objects you have defined to represent the data in the SQL table.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x