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

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

Интервал:

Закладка:

Сделать
Interface Description
ICollection<(Of <(T>)>) Defines methods to manipulate generic collections
IComparer<(Of <(T>)>) Defines a method that a type implements to compare two objects
IDictionary<(Of <(TKey, TValue>)>) Represents a generic collection of key/value pairs
IEnumerable<(Of <(T>)>) Exposes the enumerator, which supports a simple iteration over a collection of a specified type
IEnumerator<(Of <(T>)>) Supports a simple iteration over a generic collection
IEqualityComparer<(Of <(T>)>) Defines methods to support the comparison of objects for equality
Ilist<(Of <(T>)>) Represents a collection of objects that can be individually accessed by index

Prior to .NET 2.0, all the data structures contained in the System.Collectionnamespace are object-based. With .NET 2.0, Microsoft has released generic equivalents of some of these classes. The following table shows the mapping of these classes in the two namespaces.

System.Collection System.Collection.Generic
Comparer Comparer
HashTable Dictionary
LinkedList
ArrayList List
Queue Queue
SortedList SortedDictionary
Stack Stack
ICollection ICollection
System.IComparable IComparable
IDictionary IDictionary
IEnumerable IEnumerable
IEnumerator IEnumerator
IList IList

The Stack, Queue, and Dictionarygeneric classes are discussed in more detail in Chapter 13, "Collections."

Using the LinkedList Generic Class

One of the new classes in the System.Collection.Genericnamespace is the LinkedListgeneric class. A linked list is a data structure containing a series of interconnected nodes. Linked lists have wide usage in computer science and are often used to store related data.

There are several types of linked lists:

□ Singly linked list

□ Doubly linked list

□ Circularly linked list

Figure 9-5 shows a singly linked list. Every node has a field that "points" to the next node. To move from one node to another (known as list traversal ), you start from the first node and follow the links leading to the next node.

Figure 95 Figure 96 shows a doubly linked list Doubly linked list nodes - фото 142

Figure 9-5

Figure 9-6 shows a doubly linked list. Doubly linked list nodes contains an additional field to point to the previous node. You can traverse a doubly linked list in either direction. The LinkedListclass implements a doubly linked list.

Figure 96 Figure 97 shows a circularly linked list A circularly linked list - фото 143

Figure 9-6

Figure 9-7 shows a circularly linked list. A circularly linked list has its first and last node linked together. A circularly linked list can either be a singly linked list (as shown in Figure 9-5) or a doubly linked list.

Figure 97 The next example shows how to use the LinkedListclass available in - фото 144

Figure 9-7

The next example shows how to use the LinkedListclass available in the .NET Framework to store a list of random numbers. As each random number is generated, it is inserted into the linked list in numeric sorted order (from small to big). The end result is a list of sorted random numbers. Specifically, the example uses the LinkedListclass members shown in the following table.

Member Description
AddAfter() Adds a new node after an existing node
AddBefore() Adds a new node before an existing node
First Gets the first node
Last Gets the last node

Each node in the LinkedListclass is an object of type LinkedListNode. The following table shows the properties in the LinkedListNodethat are used in this example.

Property Description
Next Gets the next node
Previous Gets the previous node
Value Gets the value contained in the node

Now for the example, first create an instance of the LinkedListclass using the inttype:

LinkedList Numbers = new LinkedList();

Define the InsertNumber()function, which accepts an intparameter:

private void InsertNumber(int number) {

//---start from first node---

LinkedListNode currNode = Numbers.First;

LinkedListNode newNode = new LinkedListNode(number);

if (currNode == null) {

Numbers.AddFirst(newNode);

return;

}

while (currNode != null) {

if (currNode.Value < number) {

if (currNode.Previous != null)

//---Case 1 - add the node to the previous node---

Numbers.AddAfter(currNode.Previous, newNode);

else

//--- Case 2 - the current node is the first node---

Numbers.AddBefore(currNode, newNode);

break;

} else if (currNode.Next == null) {

//--- Case 3 - if last node has been reached---

Numbers.AddAfter(currNode, newNode);

break;

}

//---traverse to the next node---

currNode = currNode.Next;

}

}

The InsertNumber()function initially creates a new node to contain the random number generated. It then traverses the linked list to find the correct position to insert the number. Take a look at the different possible cases when inserting a number into the linked list.

Figure 9-8 shows the case when the node to be inserted (11) is between two nodes (9 and 15, the current node). In this case, it must be added after node 9.

Figure 98 Figure 99 shows the case when the node to be inserted 11 is - фото 145

Figure 9-8

Figure 9-9 shows the case when the node to be inserted (11) is smaller than the first node (current node) in the linked list. In this case, it must be added before the current node.

Figure 99 Figure 910 shows the case when the node to be inserted is larger - фото 146

Figure 9-9

Figure 9-10 shows the case when the node to be inserted is larger than the last node (current node) in the linked list. In this case, it must be added after the current node.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x