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

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

Интервал:

Закладка:

Сделать

}

}

public static IComparer SalarySorter {

get { return new SalaryComparer(); }

}

public static IComparer LastNameSorter {

get { return new LastNameComparer(); }

}

public string FirstName { get; set; }

public string LastName { get; set; }

public int Salary { get; set; }

public override string ToString() {

return FirstName + ", " + LastName + " $" + Salary;

}

public int CompareTo(Employee emp) {

return this.FirstName.CompareTo(emp.FirstName);

}

}

You can now sort by LastNameusing the LastNameSorterproperty:

employees.Sort(Employee.LastNameSorter); //---sort using LastName---

Dictionary

Most of you are familiar with the term dictionary — a reference book containing an alphabetical list of words with information about them. In computing, a dictionary object provides a mapping from a set of keys to a set of values. In .NET, this dictionary comes in the form of the Dictionaryclass (the generic equivalent is Dictionary).

The following shows how you can create a new Dictionaryobject with type int to be used for the key and type Stringto be used for the values:

Dictionary employees = new Dictionary();

To add items into a Dictionaryobject, use the Add()method:

employees.Add(1001, "Margaret Anderson");

employees.Add(1002, "Howard Mark");

employees.Add(1003, "John Smith");

employees.Add(1004, "Brian Will");

Trying to add a key that already exists in the object produces an ArgumentException error:

//---ArgumentException; duplicate key---

employees.Add(1004, "Sculley Lawrence");

A safer way is to use the ContainsKey()method to check if the key exists before adding the new key:

if (!employees.ContainsKey(1005)) {

employees.Add(1005, "Sculley Lawrence");

}

While having duplicate keys is not acceptable, you can have different keys with the same value:

employees.Add(1006, "Sculley Lawrence"); //---duplicate value is OK---

To retrieve items from the Dictionary object, simply specify the key:

Console.WriteLine(employees[1002].ToString()); //---Howard Mark---

When retrieving items from a Dictionaryobject, be certain that the key you specify is valid or you encounter a KeyNotFoundExceptionerror:

try {

//---KeyNotFoundException---

Console.WriteLine(employees[1005].ToString());

} catch (KeyNotFoundException ex) {

Console.WriteLine(ex.Message);

}

Rather than catching an exception when the specified key is not found, it's more efficient to use the TryGetValue()method:

string Emp_Name;

if (employees.TryGetValue(1005, out Emp_Name))

Console.WriteLine(Emp_Name);

TryGetValue()takes in a key for the Dictionaryobject as well as an out parameter that will contain the associated value for the specified key. If the key specified does not exist in the Dictionaryobject, the out parameter ( Emp_Name, in this case) contains the default value for the specified type (string in this case, hence the default value is null).

When you use the foreachstatement on a Dictionaryobject to iterate over all the elements in it, each Dictionary object element is retrieved as a KeyValuePairobject:

foreach (KeyValuePair Emp in employees)

Console.WriteLine("{0} - {1}", Emp.Key, Emp.Value);

Here's the output from these statements:

1001 - Margaret Anderson

1002 - Howard Mark

1003 - John Smith

1004 - Brian Will

To get all the keys in a Dictionaryobject, use the KeyCollectionclass:

//---get all the employee IDs---

Dictionary.KeyCollection

EmployeeID = employees.Keys;

foreach (int ID in EmployeeID)

Console.WriteLine(ID);

These statements print out all the keys in the Dictionary object:

1001

1002

1003

1004

If you want all the employees' names, you can use the ValueCollectionclass, like this:

//---get all the employee names---

Dictionary.ValueCollection

EmployeeNames = employees.Values;

foreach (string emp in EmployeeNames)

Console.WriteLine(emp);

You can also copy all the values in a Dictionaryobject into an array using the ToArray()method:

//---extract all the values in the Dictionary object

// and copy into the array---

string[] Names = employees.Values.ToArray();

foreach (string n in Names)

Console.WriteLine(n);

To remove a key from a Dictionaryobject, use the Remove()method, which takes the key to delete:

if (employees.ContainsKey(1006)) {

employees.Remove(1006);

}

To sort the keys in a Dictionaryobject, use the SortedDictionaryclass instead of the Dictionaryclass:

SortedDictionary employees =

new SortedDictionary< int, string>();

Stacks

A stack is a last in, first out (LIFO) data structure — the last item added to a stack is the first to be removed. Conversely, the first item added to a stack is the last to be removed.

In .NET, you can use the Stackclass (or the generic equivalent of Stack) to represent a stack collection. The following statement creates an instance of the Stackclass of type string:

Stack tasks = new Stack();

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

Интервал:

Закладка:

Сделать

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

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


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

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

x