Что такое Dictionary в C#?
Класс Dictionary представляет собой коллекцию пар «ключ-значение», где каждому ключу соответствует уникальное значение. Этот класс предоставляет эффективные методы для добавления, удаления и поиска элементов по ключу, что делает его удобным для решения задач, связанных с хранением и доступом к данным.
Особенности:
- Ассоциативное хранение данных: Dictionary предоставляет механизм ассоциативного хранения данных, где каждому ключу соответствует уникальное значение.
- Быстрый доступ к данным: Реализация на основе хэш-таблицы обеспечивает быстрый доступ к данным по ключу.
- Операции добавления и удаления: Класс предоставляет методы для добавления, удаления и изменения элементов, а также для проверки наличия ключа.
// Пример использования Dictionary для хранения информации о студентах Dictionary studentDictionary = new Dictionary(); // Добавление элементов в словарь studentDictionary.Add(1, "Alice"); studentDictionary.Add(2, "Bob"); studentDictionary.Add(3, "Charlie"); // Получение значения по ключу string studentName = studentDictionary[2]; // Проверка наличия ключа в словаре bool containsKey = studentDictionary.ContainsKey(3); // Изменение значения по ключу studentDictionary[1] = "Alicia"; // Удаление элемента по ключу studentDictionary.Remove(2); // Вывод результатов Console.WriteLine($"Имя студента с ключом 1: "); Console.WriteLine($"Наличие ключа 3: ");
C#: Как работает Dictionary в C# с примерами. Почему словарь настолько быстрая коллекция — видео HD

В этом видео рассмотрим как работают некоторые основные функции в Dictionary в C# .Net Core. Почему это такая полезная структура данных и почему она работает так быстро.
Dictionary позволяет хранить элементы в виде пар «ключ-значение» для быстрого поиска по ключу.
1. Поймем какое состояние при инициализации внутренних массивов entries и buckets
2. Добавим 4 пары и посмотрим как изменится состояние
3. Разрешим одну коллизию
4. Посмотрим как происходит расширение внутренних массивов entries и buckets
#dotnet #csharp #programming #learningprogramming #development #softwareengineering #hashset
05.02.2023 15:27
Sound language:
RUS — Русский
Провайдер видео:
Ссылка на страницу ролика: Код ролика: Код для плейлиста: Размер видео: × Отменить Автозапуск воспроизведения Код для плейлиста Начинать с текущего видео
Эффективное использование словаря (C#) как альтернатива оператору If
Всё больше наших коллег на практике предпочитают избегать применения операторов if . Эти условия, по их мнению, усложняют и прибавляют багов в наши приложения.
Но условия лежат в основе программирования, и мы не можем полностью избавиться от операторов if — мы можем лишь сократить их использование.
Что такое словарь?
Словарь — это структура данных, предназначенная для хранения группы объектов. Он может использоваться для маппинга, кэша в оперативной памяти, таблиц и т.д. Объекты хранятся в нём как коллекция пар ключ/значение, что очень удобно и характерно для разных объектно-ориентированных языков программирования. Таким же образом — в виде пар ключ/значение — могут быть заданы делегаты.
Что такое делегат?
«Делегат — это объект, который ссылается на метод. Или даже можно сказать, что это переменная ссылочного типа, которая содержит ссылку на методы. Делегаты в C# схожи с указателем на функцию в C/C++. Он помогает определить, какой метод должен вызываться при срабатывании события».
Есть два типа делегатов, которые нужны для наших примеров: Action и Func. Action используется для методов void, а Func — для методов возвращаемого типа return.
static void Main(string[] args)
Dictionary dict = new Dictionary();
dict.Add("foo", bar);
dict["foo"].Invoke();
Console.WriteLine("World");
Console.ReadLine();
>
static void bar()
Console.WriteLine("Hello");
>
Здесь определяется словарь с типом и к нему добавляется элемент, а затем выполняется метод для вызова dict[“foo”] . Можем использовать dict[“foo”]() как альтернативу dict[“foo”].Invoke() .
Какой полезный метод, правда?:)
Пример
Предположим, у нас есть модуль генерации отчётов, который создаёт периодические отчёты: ежедневные, еженедельные, ежемесячные, ежегодные и т.д. Причём они не содержат параметрического или возвращаемого типа.
Сначала он выглядит вот так:
using System;
using System.Collections.Generic;
namespace DictionaryTraining
public class Program
static void Main(string[] args)
Reporter reporter = new Reporter();
ReportType reportType = ReportType.Monthly;
PrepareReport(reportType);
Console.ReadLine();
>
private static void PrepareReport(ReportType reportType)
Reporter reporter = new Reporter();
if (reportType == ReportType.Daily)
reporter.GetDailyReport();
>
else if (reportType == ReportType.Weekly)
reporter.GetWeeklyReport();
>
else if (reportType == ReportType.Monthly)
reporter.GetMonthlyReport();
>
else if (reportType == ReportType.Annual)
reporter.GetAnnualReport();
>
>
>
public class Reporter
public void GetDailyReport()
Console.WriteLine("Daily report is preparing. ");
>
public void GetWeeklyReport()
Console.WriteLine("Weekly report is preparing. ");
>
public void GetMonthlyReport()
Console.WriteLine("Monthly report is preparing. ");
>
public void GetAnnualReport()
Console.WriteLine("Annual report is preparing. ");
>
>
public enum ReportType
Daily,
Weekly,
Monthly,
Annual
>
>
Теперь у нас есть класс Reporter с разными методами для подготовки отчётов.
Для вызова определённого метода в соответствии с типом каждого отчёта используется метод PrepareReport . Для этого будет задействовано множество операторов if-else .
Ну а мы попробуем вместо них использовать словарь и делегаты:
using System;
using System.Collections.Generic;
namespace DictionaryTraining
public class Program
static Dictionary dictReports = new Dictionary();
static void Main(string[] args)
Reporter reporter = new Reporter();
dictReports.Add(ReportType.Daily, new Action(reporter.GetDailyReport));
dictReports.Add(ReportType.Weekly, new Action(reporter.GetWeeklyReport));
dictReports.Add(ReportType.Monthly, new Action(reporter.GetMonthlyReport));
dictReports.Add(ReportType.Annual, new Action(reporter.GetAnnualReport));
dictReports[ReportType.Weekly]();
Console.ReadLine();
>
>
public class Reporter
public void GetDailyReport()
Console.WriteLine("Daily report is preparing. ");
>
public void GetWeeklyReport()
Console.WriteLine("Weekly report is preparing. ");
>
public void GetMonthlyReport()
Console.WriteLine("Monthly report is preparing. ");
>
public void GetAnnualReport()
Console.WriteLine("Annual report is preparing. ");
>
>
enum ReportType
Daily,
Weekly,
Monthly,
Annual
>
>
Словарь с типом будет использоваться в качестве делегата, а методы создания отчёта будут вызываться без необходимости проверять тип каждого отчёта.
На мой взгляд, это более читаемый и лёгкий в сопровождении код. Меньше строк — больше ясности.
Делегаты с возвращаемым типом
Если методы для подготовки отчётов имеют возвращаемый тип, должен использоваться делегат Func (но все методы должны иметь те же параметрические и возвращаемый типы).
using System;
using System.Collections.Generic;
namespace DictionaryTraining
public class Program
static Dictionary> dictReports = new Dictionary>();
static void Main(string[] args)
Reporter reporter = new Reporter();
dictReports.Add(ReportType.Daily, new Func(reporter.GetDailyReport));
dictReports.Add(ReportType.Weekly, new Func(reporter.GetWeeklyReport));
dictReports.Add(ReportType.Monthly, new Func(reporter.GetMonthlyReport));
dictReports.Add(ReportType.Annual, new Func(reporter.GetAnnualReport));
dictReports[ReportType.Daily](60);
Console.ReadLine();
>
>
public class Reporter
public string GetDailyReport(int dayOfYear)
Console.WriteLine("Daily report is preparing. ");
return "report of day: " + dayOfYear;
>
public string GetWeeklyReport(int weekOfYear)
Console.WriteLine("Weekly report is preparing. ");
return "report of week: " + weekOfYear;
>
public string GetMonthlyReport(int monthOfYear)
Console.WriteLine("Monthly report is preparing. ");
return "report of month: " + monthOfYear;
>
public string GetAnnualReport(int year)
Console.WriteLine("Annual report is preparing. ");
return "report of year: " + year;
>
>
enum ReportType
Daily,
Weekly,
Monthly,
Annual
>
>
И вот результат:
А сколько ещё есть вариантов применения словаря с точки зрения роста показателей производительности!
- Разбираемся с компилятором Go
- Строковые методы в Python
- Топ-10 самых распространенных ошибок в проектах Go. Часть 1
Dictionary c что это
Dictionary это класс храняющий набор пар «ключ-значение».
Dictionary относится к типизированной коллекции. то есть все элементы одного типа.
Пример Dictionary
C# Создаем новое C# консольное приложение. и напишем код
using System;
using System.Collections.Generic; // подключаем Dictionary
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
<
class Program
<
static void Main( string [] args)
<
// создаем Dictionary
Dictionary < string , string >dict = new Dictionary< string , string >();
// добавляем элементы
dict.Add( «txt» /*ключ*/ , «notepad.exe» /*значение*/ );
dict.Add( «bmp» /*ключ*/ , «paint.exe» /*значение*/ );
dict.Add( «dib» /*ключ*/ , «paint.exe» /*значение*/ );
dict.Add( «rtf» /*ключ*/ , «wordpad.exe» /*значение*/ );
// в dict элементы:
//
//
//
//
// Вариант 1 (перебираем все элементы с помощью foreach и выводим на экран)
foreach ( string key in dict.Keys) // перебираем все ключи
Console .WriteLine( «Ключ=» + key + » , значение=» + dict[key]); // получаем значение
// на экране увидим «Ключ=txt , значение=notepad.exe»
// на экране увидим «Ключ=bmp , значение=paint.exe»
// на экране увидим «Ключ=dib , значение=paint.exe»
// на экране увидим «Ключ=rtf , значение=wordpad.exe»
// Dictionary не сотрирует значения по ключу
// Вариант 2 (перебираем все элементы с помощью foreach и выводим на экран)
foreach (KeyValuePair < string , string >item in dict)
Console .WriteLine( «Ключ=» + item.Key + » , значение=» + item.Value);
// на экране увидим «Ключ=txt , значение=notepad.exe»
// на экране увидим «Ключ=bmp , значение=paint.exe»
// на экране увидим «Ключ=dib , значение=paint.exe»
// на экране увидим «Ключ=rtf , значение=wordpad.exe»
// Dictionary не сотрирует значения по ключу
// Вариант 1. Получить значение по ключу (не будет exception если ключа не существует)
string value;
if (dict.TryGetValue( «ooo» , out value))
Console .WriteLine(value);
// Вариант 2. получить значение по ключу (будет EXCEPTION если ключа не существует)
try
<
value = dict[ «vvv» ];
>
catch (KeyNotFoundException e)
<
Console .WriteLine(e.Message); // key not found
>
// узнать есть ли такой ключ (не будет exception если ключа не существует)
bool isFound = dict.ContainsKey( «iii» );
// isFound = false
Описание Dictionary
Dictionary относится к типизированной коллекции. то есть все элементы одного типа.
Dictionary это класс храняющий набор пар «ключ-значение».
Версия .NETFrameworkv4.6.1mscorlib.dll
Синтаксис
public class Dictionary : IDictionary , ICollection>, IEnumerable>, IEnumerable, IDictionary, ICollection, IReadOnlyDictionary, IReadOnlyCollection>, ISerializable, IDeserializationCallback
Конструкторы
![]()
public Dictionary ();
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
![]()
public Dictionary (int capacity);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type. Полное описание .
Parameters:
capacity:
The initial number of elements that the System.Collections.Generic.Dictionary`2
can contain.
Exceptions:
T:System.ArgumentOutOfRangeException:
capacity is less than 0.
![]()
public Dictionary (IEqualityComparer comparer);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that is empty, has the default initial capacity, and uses the specified System.Collections.Generic.IEqualityComparer`1. Полное описание .
Parameters:
comparer:
The System.Collections.Generic.IEqualityComparer`1 implementation to use when
comparing keys, or null to use the default System.Collections.Generic.EqualityComparer`1
for the type of the key.
![]()
public Dictionary (IDictionary dictionary);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that contains elements copied from the specified System.Collections.Generic.IDictionary`2 and uses the default equality comparer for the key type. Полное описание .
Parameters:
dictionary:
The System.Collections.Generic.IDictionary`2 whose elements are copied to the
new System.Collections.Generic.Dictionary`2.
Exceptions:
T:System.ArgumentNullException:
dictionary is null.
T:System.ArgumentException:
dictionary contains one or more duplicate keys.
![]()
public Dictionary (int capacity, IEqualityComparer comparer);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that is empty, has the specified initial capacity, and uses the specified System.Collections.Generic.IEqualityComparer`1. Полное описание .
Parameters:
capacity:
The initial number of elements that the System.Collections.Generic.Dictionary`2
can contain.
comparer:
The System.Collections.Generic.IEqualityComparer`1 implementation to use when
comparing keys, or null to use the default System.Collections.Generic.EqualityComparer`1
for the type of the key.
Exceptions:
T:System.ArgumentOutOfRangeException:
capacity is less than 0.
![]()
public Dictionary (IDictionary dictionary, IEqualityComparer comparer);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class that contains elements copied from the specified System.Collections.Generic.IDictionary`2 and uses the specified System.Collections.Generic.IEqualityComparer`1. Полное описание .
Parameters:
dictionary:
The System.Collections.Generic.IDictionary`2 whose elements are copied to the
new System.Collections.Generic.Dictionary`2.
comparer:
The System.Collections.Generic.IEqualityComparer`1 implementation to use when
comparing keys, or null to use the default System.Collections.Generic.EqualityComparer`1
for the type of the key.
Exceptions:
T:System.ArgumentNullException:
dictionary is null.
T:System.ArgumentException:
dictionary contains one or more duplicate keys.
![]()
protected Dictionary (SerializationInfo info, StreamingContext context);
Initializes a new instance of the System.Collections.Generic.Dictionary`2 class with serialized data. Полное описание .
Parameters:
info:
A System.Runtime.Serialization.SerializationInfo object containing the information
required to serialize the System.Collections.Generic.Dictionary`2.
context:
A System.Runtime.Serialization.StreamingContext structure containing the source
and destination of the serialized stream associated with the System.Collections.Generic.Dictionary`2.
Свойства
![]()
public TValue this[TKey key] < get; set; >
Gets or sets the value associated with the specified key. Полное описание .
Parameters:
key:
The key of the value to get or set.
Exceptions:
The value associated with the specified key. If the specified key is not found,
a get operation throws a System.Collections.Generic.KeyNotFoundException, and
a set operation creates a new element with the specified key.
Exceptions:
T:System.ArgumentNullException:
key is null.
T:System.Collections.Generic.KeyNotFoundException:
The property is retrieved and key does not exist in the collection.
![]()
public ValueCollection Values < get; >
Gets a collection containing the values in the System.Collections.Generic.Dictionary`2. Полное описание .
Exceptions:
A System.Collections.Generic.Dictionary`2.ValueCollection containing the values
in the System.Collections.Generic.Dictionary`2.
![]()
public KeyCollection Keys < get; >
Gets a collection containing the keys in the System.Collections.Generic.Dictionary`2. Полное описание .
Exceptions:
A System.Collections.Generic.Dictionary`2.KeyCollection containing the keys in
the System.Collections.Generic.Dictionary`2.
![]()
public int Count < get; >
Gets the number of key/value pairs contained in the System.Collections.Generic.Dictionary`2. Полное описание .
Exceptions:
The number of key/value pairs contained in the System.Collections.Generic.Dictionary`2.
![]()
public IEqualityComparer Comparer < get; >
Gets the System.Collections.Generic.IEqualityComparer`1 that is used to determine equality of keys for the dictionary. Полное описание .
Exceptions:
The System.Collections.Generic.IEqualityComparer`1 generic interface implementation
that is used to determine equality of keys for the current System.Collections.Generic.Dictionary`2
and to provide hash values for the keys.
Методика
![]()
public void Add (TKey key, TValue value);
Adds the specified key and value to the dictionary. Полное описание .
Parameters:
key:
The key of the element to add.
value:
The value of the element to add. The value can be null for reference types.
Exceptions:
T:System.ArgumentNullException:
key is null.
T:System.ArgumentException:
An element with the same key already exists in the System.Collections.Generic.Dictionary`2.
![]()
public void Clear ();
Removes all keys and values from the System.Collections.Generic.Dictionary`2.
![]()
public bool ContainsKey (TKey key);
Determines whether the System.Collections.Generic.Dictionary`2 contains the specified key. Полное описание .
Parameters:
key:
The key to locate in the System.Collections.Generic.Dictionary`2.
Exceptions:
true if the System.Collections.Generic.Dictionary`2 contains an element with
the specified key; otherwise, false.
Exceptions:
T:System.ArgumentNullException:
key is null.
![]()
public bool ContainsValue (TValue value);
Determines whether the System.Collections.Generic.Dictionary`2 contains a specific value. Полное описание .
Parameters:
value:
The value to locate in the System.Collections.Generic.Dictionary`2. The value
can be null for reference types.
Exceptions:
true if the System.Collections.Generic.Dictionary`2 contains an element with
the specified value; otherwise, false.
![]()
public Enumerator GetEnumerator ();
Returns an enumerator that iterates through the System.Collections.Generic.Dictionary`2. Полное описание .
Exceptions:
A System.Collections.Generic.Dictionary`2.Enumerator structure for the System.Collections.Generic.Dictionary`2.
![]()
public virtual void GetObjectData (SerializationInfo info, StreamingContext context);
Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the System.Collections.Generic.Dictionary`2 instance. Полное описание .
Parameters:
info:
A System.Runtime.Serialization.SerializationInfo object that contains the information
required to serialize the System.Collections.Generic.Dictionary`2 instance.
context:
A System.Runtime.Serialization.StreamingContext structure that contains the source
and destination of the serialized stream associated with the System.Collections.Generic.Dictionary`2
instance.
Exceptions:
T:System.ArgumentNullException:
info is null.
![]()
public virtual void OnDeserialization (object sender);
Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete. Полное описание .
Parameters:
sender:
The source of the deserialization event.
Exceptions:
T:System.Runtime.Serialization.SerializationException:
The System.Runtime.Serialization.SerializationInfo object associated with the
current System.Collections.Generic.Dictionary`2 instance is invalid.
![]()
public bool Remove (TKey key);
Removes the value with the specified key from the System.Collections.Generic.Dictionary`2. Полное описание .
Parameters:
key:
The key of the element to remove.
Exceptions:
true if the element is successfully found and removed; otherwise, false. This
method returns false if key is not found in the System.Collections.Generic.Dictionary`2.
Exceptions:
T:System.ArgumentNullException:
key is null.
![]()
public bool TryGetValue (TKey key, out TValue value);
Gets the value associated with the specified key. Полное описание .
Parameters:
key:
The key of the value to get.
value:
When this method returns, contains the value associated with the specified key,
if the key is found; otherwise, the default value for the type of the value parameter.
This parameter is passed uninitialized.
Exceptions:
true if the System.Collections.Generic.Dictionary`2 contains an element with
the specified key; otherwise, false.
Exceptions:
T:System.ArgumentNullException:
key is null.
public sealed class KeyCollection : ICollection, IEnumerable, IEnumerable, ICollection, IReadOnlyCollection
![]()
public KeyCollection (Dictionary dictionary);
Initializes a new instance of the System.Collections.Generic.Dictionary`2.KeyCollection class that reflects the keys in the specified System.Collections.Generic.Dictionary`2. Полное описание .
Parameters:
dictionary:
The System.Collections.Generic.Dictionary`2 whose keys are reflected in the new
System.Collections.Generic.Dictionary`2.KeyCollection.
Exceptions:
T:System.ArgumentNullException:
dictionary is null.
![]()
public int Count < get; >
Gets the number of elements contained in the System.Collections.Generic.Dictionary`2.KeyCollection. Полное описание .
Exceptions:
The number of elements contained in the System.Collections.Generic.Dictionary`2.KeyCollection.Retrieving
the value of this property is an O(1) operation.
![]()
public void CopyTo (TKey[] array, int index);
Copies the System.Collections.Generic.Dictionary`2.KeyCollection elements to an existing one-dimensional System.Array, starting at the specified array index. Полное описание .
Parameters:
array:
The one-dimensional System.Array that is the destination of the elements copied
from System.Collections.Generic.Dictionary`2.KeyCollection. The System.Array
must have zero-based indexing.
index:
The zero-based index in array at which copying begins.
Exceptions:
T:System.ArgumentNullException:
array is null.
T:System.ArgumentOutOfRangeException:
index is less than zero.
T:System.ArgumentException:
The number of elements in the source System.Collections.Generic.Dictionary`2.KeyCollection
is greater than the available space from index to the end of the destination
array.
![]()
public Enumerator GetEnumerator ();
Returns an enumerator that iterates through the System.Collections.Generic.Dictionary`2.KeyCollection. Полное описание .
Exceptions:
A System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator for the System.Collections.Generic.Dictionary`2.KeyCollection.
public sealed class ValueCollection : ICollection, IEnumerable, IEnumerable, ICollection, IReadOnlyCollection
![]()
public ValueCollection (Dictionary dictionary);
Initializes a new instance of the System.Collections.Generic.Dictionary`2.ValueCollection class that reflects the values in the specified System.Collections.Generic.Dictionary`2. Полное описание .
Parameters:
dictionary:
The System.Collections.Generic.Dictionary`2 whose values are reflected in the
new System.Collections.Generic.Dictionary`2.ValueCollection.
Exceptions:
T:System.ArgumentNullException:
dictionary is null.
![]()
public int Count < get; >
Gets the number of elements contained in the System.Collections.Generic.Dictionary`2.ValueCollection. Полное описание .
Exceptions:
The number of elements contained in the System.Collections.Generic.Dictionary`2.ValueCollection.
![]()
public void CopyTo (TValue[] array, int index);
Copies the System.Collections.Generic.Dictionary`2.ValueCollection elements to an existing one-dimensional System.Array, starting at the specified array index. Полное описание .
Parameters:
array:
The one-dimensional System.Array that is the destination of the elements copied
from System.Collections.Generic.Dictionary`2.ValueCollection. The System.Array
must have zero-based indexing.
index:
The zero-based index in array at which copying begins.
Exceptions:
T:System.ArgumentNullException:
array is null.
T:System.ArgumentOutOfRangeException:
index is less than zero.
T:System.ArgumentException:
The number of elements in the source System.Collections.Generic.Dictionary`2.ValueCollection
is greater than the available space from index to the end of the destination
array.
![]()
public Enumerator GetEnumerator ();
Returns an enumerator that iterates through the System.Collections.Generic.Dictionary`2.ValueCollection. Полное описание .
Exceptions:
A System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator for the
System.Collections.Generic.Dictionary`2.ValueCollection.
Почему метод Dictionary.TryGetValue не может найти значение по ключу в C# ?
C# Создаем новое C# консольное приложение. и напишем код
using System;
using System.Collections.Generic; // подключаем Dictionary
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
<
class Book
<
public string BookName < set; get; >
public string AuthorName < set; get; >
>
class Program
<
static void Main( string [] args)
<
// создаем List
Dictionary books = new Dictionary();
// ищем книгу
Book findBook = new Book() < BookName = "Три мушкетера" , AuthorName = "Дюма" >;
int price = 0;
if (books.TryGetValue(findBook, out price))
<
Console .WriteLine( «Найдено! Название:, Автор:, Цена:» , findBook.BookName, findBook.AuthorName, price);
>
else
<
Console .WriteLine( «Не найдено» );
>
// на экране увидим «Не найдено»
>
>
>
Чтобы искалось не по ссылке объекта а по содержимому нужно написать 2 метода для Book :
public override bool Equals (Object obj)
<
.
>
public override int GetHashCode ()
<
.
>
C# Решение. Полный код.
using System;
using System.Collections.Generic; // подключаем Dictionary
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
<
class Book
<
public string BookName < set; get; >
public string AuthorName
public override bool Equals (Object obj)
<
Book book = obj as Book;
return (BookName.CompareTo(book.BookName) == 0 && AuthorName.CompareTo(book.AuthorName) == 0);
>
public override int GetHashCode ()
<
unchecked
<
return BookName.GetHashCode() + AuthorName.GetHashCode();
>
>
>
class Program
<
static void Main( string [] args)
<
// создаем List
Dictionary books = new Dictionary();
// ищем книгу
Book findBook = new Book() < BookName = "Три мушкетера" , AuthorName = "Дюма" >;
int price = 0;
if (books.TryGetValue(findBook, out price))
<
Console .WriteLine( «Найдено! Название:, Автор:, Цена:» , findBook.BookName, findBook.AuthorName, price);
>
else
<
Console .WriteLine( «Не найдено» );
>
// на экране увидим «Найдено! Название:Три мушкетера, Автор:Дюма, Цена:200»
>
>
>