OrderedDictionary Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет коллекцию пар "ключ-значение", доступных ключом или индексом.
public ref class OrderedDictionary : System::Collections::IDictionary, System::Collections::Specialized::IOrderedDictionary
public ref class OrderedDictionary : System::Collections::IDictionary, System::Collections::Specialized::IOrderedDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public ref class OrderedDictionary : System::Collections::Specialized::IOrderedDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class OrderedDictionary : System.Collections.IDictionary, System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
public class OrderedDictionary : System.Collections.Specialized.IOrderedDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type OrderedDictionary = class
interface ICollection
interface IEnumerable
interface IDictionary
interface IOrderedDictionary
type OrderedDictionary = class
interface ICollection
interface IEnumerable
interface IDictionary
interface IOrderedDictionary
interface IDeserializationCallback
interface ISerializable
type OrderedDictionary = class
interface ICollection
interface IEnumerable
interface IDictionary
interface IOrderedDictionary
interface ISerializable
interface IDeserializationCallback
[<System.Serializable>]
type OrderedDictionary = class
interface IOrderedDictionary
interface IDictionary
interface ICollection
interface IEnumerable
interface ISerializable
interface IDeserializationCallback
Public Class OrderedDictionary
Implements IDictionary, IOrderedDictionary
Public Class OrderedDictionary
Implements IDeserializationCallback, IDictionary, IOrderedDictionary, ISerializable
Public Class OrderedDictionary
Implements IDeserializationCallback, IOrderedDictionary, ISerializable
- Наследование
-
OrderedDictionary
- Производный
- Атрибуты
- Реализации
Примеры
В следующем примере кода демонстрируется создание, заполнение и изменение OrderedDictionary коллекции, а также два метода отображения содержимого OrderedDictionary: один с помощью Keys свойств и Values другого создания перечислителя с помощью GetEnumerator метода.
// The following code example enumerates the elements of a OrderedDictionary.
using System;
using System.Collections;
using System.Collections.Specialized;
public class OrderedDictionarySample
{
public static void Main()
{
// Creates and initializes a OrderedDictionary.
OrderedDictionary myOrderedDictionary = new OrderedDictionary();
myOrderedDictionary.Add("testKey1", "testValue1");
myOrderedDictionary.Add("testKey2", "testValue2");
myOrderedDictionary.Add("keyToDelete", "valueToDelete");
myOrderedDictionary.Add("testKey3", "testValue3");
ICollection keyCollection = myOrderedDictionary.Keys;
ICollection valueCollection = myOrderedDictionary.Values;
// Display the contents using the key and value collections
DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);
// Modifying the OrderedDictionary
if (!myOrderedDictionary.IsReadOnly)
{
// Insert a new key to the beginning of the OrderedDictionary
myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1");
// Modify the value of the entry with the key "testKey2"
myOrderedDictionary["testKey2"] = "modifiedValue";
// Remove the last entry from the OrderedDictionary: "testKey3"
myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1);
// Remove the "keyToDelete" entry, if it exists
if (myOrderedDictionary.Contains("keyToDelete"))
{
myOrderedDictionary.Remove("keyToDelete");
}
}
Console.WriteLine(
"{0}Displaying the entries of a modified OrderedDictionary.",
Environment.NewLine);
DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);
// Clear the OrderedDictionary and add new values
myOrderedDictionary.Clear();
myOrderedDictionary.Add("newKey1", "newValue1");
myOrderedDictionary.Add("newKey2", "newValue2");
myOrderedDictionary.Add("newKey3", "newValue3");
// Display the contents of the "new" Dictionary using an enumerator
IDictionaryEnumerator myEnumerator =
myOrderedDictionary.GetEnumerator();
Console.WriteLine(
"{0}Displaying the entries of a \"new\" OrderedDictionary.",
Environment.NewLine);
DisplayEnumerator(myEnumerator);
}
// Displays the contents of the OrderedDictionary from its keys and values
public static void DisplayContents(
ICollection keyCollection, ICollection valueCollection, int dictionarySize)
{
String[] myKeys = new String[dictionarySize];
String[] myValues = new String[dictionarySize];
keyCollection.CopyTo(myKeys, 0);
valueCollection.CopyTo(myValues, 0);
// Displays the contents of the OrderedDictionary
Console.WriteLine(" INDEX KEY VALUE");
for (int i = 0; i < dictionarySize; i++)
{
Console.WriteLine(" {0,-5} {1,-25} {2}",
i, myKeys[i], myValues[i]);
}
Console.WriteLine();
}
// Displays the contents of the OrderedDictionary using its enumerator
public static void DisplayEnumerator(IDictionaryEnumerator myEnumerator)
{
Console.WriteLine(" KEY VALUE");
while (myEnumerator.MoveNext())
{
Console.WriteLine(" {0,-25} {1}",
myEnumerator.Key, myEnumerator.Value);
}
}
}
/*
This code produces the following output.
INDEX KEY VALUE
0 testKey1 testValue1
1 testKey2 testValue2
2 keyToDelete valueToDelete
3 testKey3 testValue3
Displaying the entries of a modified OrderedDictionary.
INDEX KEY VALUE
0 insertedKey1 insertedValue1
1 testKey1 testValue1
2 testKey2 modifiedValue
Displaying the entries of a "new" OrderedDictionary.
KEY VALUE
newKey1 newValue1
newKey2 newValue2
newKey3 newValue3
*/
' The following code example enumerates the elements of a OrderedDictionary.
Imports System.Collections
Imports System.Collections.Specialized
Public Class OrderedDictionarySample
Public Shared Sub Main()
' Creates and initializes a OrderedDictionary.
Dim myOrderedDictionary As New OrderedDictionary()
myOrderedDictionary.Add("testKey1", "testValue1")
myOrderedDictionary.Add("testKey2", "testValue2")
myOrderedDictionary.Add("keyToDelete", "valueToDelete")
myOrderedDictionary.Add("testKey3", "testValue3")
Dim keyCollection As ICollection = myOrderedDictionary.Keys
Dim valueCollection As ICollection = myOrderedDictionary.Values
' Display the contents Imports the key and value collections
DisplayContents( _
keyCollection, valueCollection, myOrderedDictionary.Count)
' Modifying the OrderedDictionary
If Not myOrderedDictionary.IsReadOnly Then
' Insert a new key to the beginning of the OrderedDictionary
myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1")
' Modify the value of the entry with the key "testKey2"
myOrderedDictionary("testKey2") = "modifiedValue"
' Remove the last entry from the OrderedDictionary: "testKey3"
myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1)
' Remove the "keyToDelete" entry, if it exists
If (myOrderedDictionary.Contains("keyToDelete")) Then
myOrderedDictionary.Remove("keyToDelete")
End If
End If
Console.WriteLine( _
"{0}Displaying the entries of a modified OrderedDictionary.", _
Environment.NewLine)
DisplayContents( _
keyCollection, valueCollection, myOrderedDictionary.Count)
' Clear the OrderedDictionary and add new values
myOrderedDictionary.Clear()
myOrderedDictionary.Add("newKey1", "newValue1")
myOrderedDictionary.Add("newKey2", "newValue2")
myOrderedDictionary.Add("newKey3", "newValue3")
' Display the contents of the "new" Dictionary Imports an enumerator
Dim myEnumerator As IDictionaryEnumerator = _
myOrderedDictionary.GetEnumerator()
Console.WriteLine( _
"{0}Displaying the entries of a 'new' OrderedDictionary.", _
Environment.NewLine)
DisplayEnumerator(myEnumerator)
End Sub
' Displays the contents of the OrderedDictionary from its keys and values
Public Shared Sub DisplayContents( _
ByVal keyCollection As ICollection, _
ByVal valueCollection As ICollection, ByVal dictionarySize As Integer)
Dim myKeys(dictionarySize) As [String]
Dim myValues(dictionarySize) As [String]
keyCollection.CopyTo(myKeys, 0)
valueCollection.CopyTo(myValues, 0)
' Displays the contents of the OrderedDictionary
Console.WriteLine(" INDEX KEY VALUE")
Dim i As Integer
For i = 0 To dictionarySize - 1
Console.WriteLine(" {0,-5} {1,-25} {2}", _
i, myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
' Displays the contents of the OrderedDictionary using its enumerator
Public Shared Sub DisplayEnumerator( _
ByVal myEnumerator As IDictionaryEnumerator)
Console.WriteLine(" KEY VALUE")
While myEnumerator.MoveNext()
Console.WriteLine(" {0,-25} {1}", _
myEnumerator.Key, myEnumerator.Value)
End While
End Sub
End Class
'This code produces the following output.
'
' INDEX KEY VALUE
'0: testKey1(testValue1)
'1: testKey2(testValue2)
'2: keyToDelete(valueToDelete)
'3: testKey3(testValue3)
'
'
'Displaying the entries of a modified OrderedDictionary.
' INDEX KEY VALUE
'0: insertedKey1(insertedValue1)
'1: testKey1(testValue1)
'2: testKey2(modifiedValue)
'
'
'Displaying the entries of a "new" OrderedDictionary.
' KEY(VALUE)
' newKey1(newValue1)
' newKey2(newValue2)
' newKey3(newValue3)
Комментарии
Каждый элемент представляет собой пару "ключ-значение", хранящуюся в объекте DictionaryEntry . Ключ не может быть null, но значение может быть.
Элементы объекта OrderedDictionary не отсортированы по ключу, в отличие от элементов SortedDictionary<TKey,TValue> класса. Доступ к элементам можно получить по ключу или по индексу.
Оператор foreach языка C# (For Each в Visual Basic) возвращает объекты, которые относятся к типу каждого элемента в коллекции. Так как каждый элемент коллекции является парой "ключ-значение", тип элемента OrderedDictionary не является типом ключа или типа значения. Вместо этого тип элемента имеет тип DictionaryEntry. В следующем коде показан синтаксис.
foreach (DictionaryEntry de in myOrderedDictionary)
{
//...
}
For Each de As DictionaryEntry In myOrderedDictionary
'...
Next de
Оператор foreach представляет собой оболочку вокруг перечислителя, которая позволяет только читать из коллекции, а не записывать в нее.
Конструкторы
| Имя | Описание |
|---|---|
| OrderedDictionary() |
Инициализирует новый экземпляр класса OrderedDictionary. |
| OrderedDictionary(IEqualityComparer) |
Инициализирует новый экземпляр класса с помощью указанного OrderedDictionary средства сравнения. |
| OrderedDictionary(Int32, IEqualityComparer) |
Инициализирует новый экземпляр класса с помощью указанной OrderedDictionary начальной емкости и средства сравнения. |
| OrderedDictionary(Int32) |
Инициализирует новый экземпляр класса с помощью указанной OrderedDictionary начальной емкости. |
| OrderedDictionary(SerializationInfo, StreamingContext) |
Устаревшие..
Инициализирует новый экземпляр OrderedDictionary класса, сериализуемого с помощью указанных SerializationInfo и StreamingContext объектов. |
Свойства
| Имя | Описание |
|---|---|
| Count |
Возвращает количество пар "ключ-значения", содержащихся в OrderedDictionary коллекции. |
| IsReadOnly |
Возвращает значение, указывающее, доступна ли OrderedDictionary коллекция только для чтения. |
| Item[Int32] |
Возвращает или задает значение по указанному индексу. |
| Item[Object] |
Возвращает или задает значение с указанным ключом. |
| Keys |
ICollection Возвращает объект, содержащий ключи в OrderedDictionary коллекции. |
| Values |
ICollection Возвращает объект, содержащий значения в OrderedDictionary коллекции. |
Методы
| Имя | Описание |
|---|---|
| Add(Object, Object) |
Добавляет запись с указанным ключом и значением в OrderedDictionary коллекцию с наименьшим доступным индексом. |
| AsReadOnly() |
Возвращает копию текущей OrderedDictionary коллекции только для чтения. |
| Clear() |
Удаляет все элементы из OrderedDictionary коллекции. |
| Contains(Object) |
Определяет, содержит ли OrderedDictionary коллекция определенный ключ. |
| CopyTo(Array, Int32) |
Копирует элементы в OrderedDictionary одномерный Array объект по указанному индексу. |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetEnumerator() |
IDictionaryEnumerator Возвращает объект, который выполняет итерацию по OrderedDictionary коллекции. |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Устаревшие..
ISerializable Реализует интерфейс и возвращает данные, необходимые для сериализации OrderedDictionary коллекции. |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| Insert(Int32, Object, Object) |
Вставляет новую запись в OrderedDictionary коллекцию с указанным ключом и значением по указанному индексу. |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| OnDeserialization(Object) |
ISerializable Реализует интерфейс и вызывается событием десериализации при завершении десериализации. |
| Remove(Object) |
Удаляет запись с указанным ключом из OrderedDictionary коллекции. |
| RemoveAt(Int32) |
Удаляет запись по указанному индексу OrderedDictionary из коллекции. |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| ICollection.IsSynchronized |
Возвращает значение, указывающее, синхронизирован ли доступ к OrderedDictionary объекту (потокобезопасный). |
| ICollection.SyncRoot |
Возвращает объект, который можно использовать для синхронизации доступа к объекту OrderedDictionary . |
| IDeserializationCallback.OnDeserialization(Object) |
ISerializable Реализует интерфейс и вызывается событием десериализации при завершении десериализации. |
| IDictionary.IsFixedSize |
Возвращает значение, указывающее, имеет ли OrderedDictionary размер фиксированного размера. |
| IEnumerable.GetEnumerator() |
IDictionaryEnumerator Возвращает объект, который выполняет итерацию по OrderedDictionary коллекции. |
Методы расширения
| Имя | Описание |
|---|---|
| AsParallel(IEnumerable) |
Включает параллелизацию запроса. |
| AsQueryable(IEnumerable) |
Преобразует IEnumerable в IQueryable. |
| Cast<TResult>(IEnumerable) |
Приведение элементов IEnumerable к указанному типу. |
| OfType<TResult>(IEnumerable) |
Фильтрует элементы IEnumerable на основе указанного типа. |