Dictionary<TKey,TValue> Konstruktorer
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Initierar en ny instans av Dictionary<TKey,TValue> klassen.
Överlagringar
| Name | Description |
|---|---|
| Dictionary<TKey,TValue>() |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har standardinitieringskapaciteten och använder standardjämförlikningsjämföraren för nyckeltypen. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IDictionary<TKey,TValue> och använder standardjämförlikningsjämföraren för nyckeltypen. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IEnumerable<T>. |
| Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har standardinitieringskapaciteten och använder den angivna IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har den angivna initiala kapaciteten och använder standardjämförlikningsjämföraren för nyckeltypen. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IDictionary<TKey,TValue> och använder den angivna IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IEnumerable<T> och använder den angivna IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har den angivna initiala kapaciteten och använder den angivna IEqualityComparer<T>. |
| Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
Initierar en ny instans av Dictionary<TKey,TValue> klassen med serialiserade data. |
Dictionary<TKey,TValue>()
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har standardinitieringskapaciteten och använder standardjämförlikningsjämföraren för nyckeltypen.
public:
Dictionary();
public Dictionary();
Public Sub New ()
Exempel
I följande kodexempel skapas en tom Dictionary<TKey,TValue> sträng med strängnycklar och metoden används Add för att lägga till vissa element. Exemplet visar att Add metoden genererar en ArgumentException när du försöker lägga till en dubblettnyckel.
Det här kodexemplet är en del av ett större exempel för Dictionary<TKey,TValue> klassen.
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
let openWith = Dictionary<string, string>()
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// The Add method throws an exception if the new key is
// already in the dictionary.
try
openWith.Add("txt", "winword.exe")
with :? ArgumentException ->
printfn "An element with Key = \"txt\" already exists."
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' The Add method throws an exception if the new key is
' already in the dictionary.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
Kommentarer
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt standardjämförlikningsjämföraren.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Den här konstruktorn använder standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen. Du kan också ange en implementering av det IEqualityComparer<T> allmänna gränssnittet med hjälp av en konstruktor som accepterar en comparer parameter.
Note
Om du kan uppskatta samlingens storlek eliminerar en konstruktor som anger den initiala kapaciteten behovet av att utföra ett antal storleksändringsåtgärder samtidigt som element läggs till i Dictionary<TKey,TValue>.
Den här konstruktorn är en O(1)-åtgärd.
Se även
Gäller för
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IDictionary<TKey,TValue> och använder standardjämförlikningsjämföraren för nyckeltypen.
public:
Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary);
public Dictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue))
Parametrar
- dictionary
- IDictionary<TKey,TValue>
Vars IDictionary<TKey,TValue> element kopieras till den nya Dictionary<TKey,TValue>.
Undantag
dictionary är null.
dictionary innehåller en eller flera dubblettnycklar.
Exempel
I följande kodexempel visas hur du använder Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktorn för att initiera en Dictionary<TKey,TValue> med sorterat innehåll från en annan ordlista. Kodexemplet skapar en SortedDictionary<TKey,TValue> och fyller den med data i slumpmässig ordning och skickar SortedDictionary<TKey,TValue> sedan till Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktorn och skapar en Dictionary<TKey,TValue> som är sorterad. Det här är användbart om du behöver skapa en sorterad ordlista som någon gång blir statisk. att kopiera data från en SortedDictionary<TKey,TValue> till en Dictionary<TKey,TValue> förbättrar hämtningshastigheten.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new sorted dictionary of strings, with string
// keys.
SortedDictionary<string, string> openWith =
new SortedDictionary<string, string>();
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// Create a Dictionary of strings with string keys, and
// initialize it with the contents of the sorted dictionary.
Dictionary<string, string> copy =
new Dictionary<string, string>(openWith);
// List the contents of the copy.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in copy )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
}
}
/* This code example produces the following output:
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
*/
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys.
let openWith = SortedDictionary<string, string>()
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Create a Dictionary of strings with string keys, and
// initialize it with the contents of the sorted dictionary.
let copy = Dictionary<string, string> openWith
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = bmp, Value = paint.exe
// Key = dib, Value = paint.exe
// Key = rtf, Value = wordpad.exe
// Key = txt, Value = notepad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new sorted dictionary of strings, with string
' keys.
Dim openWith As New SortedDictionary(Of String, String)
' Add some elements to the sorted dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Create a Dictionary of strings with string keys, and
' initialize it with the contents of the sorted dictionary.
Dim copy As New Dictionary(Of String, String)(openWith)
' List the contents of the copy.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In copy
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
Kommentarer
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt standardjämlikhetsjämföraren. På samma sätt måste varje nyckel i källan dictionary också vara unik enligt standardjämlikhetsjämföraren.
Den ursprungliga kapaciteten för den nya Dictionary<TKey,TValue> är tillräckligt stor för att innehålla alla element i dictionary.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Den här konstruktorn använder standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen. Du kan också ange en implementering av det IEqualityComparer<T> allmänna gränssnittet med hjälp av en konstruktor som accepterar en comparer parameter.
Den här konstruktorn är en O(n)-åtgärd, där n är antalet element i dictionary.
Se även
Gäller för
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IEnumerable<T>.
public:
Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection);
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)))
Parametrar
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Vars IEnumerable<T> element kopieras till den nya Dictionary<TKey,TValue>.
Undantag
collection är null.
collection innehåller en eller flera duplicerade nycklar.
Gäller för
Dictionary<TKey,TValue>(IEqualityComparer<TKey>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har standardinitieringskapaciteten och använder den angivna IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (comparer As IEqualityComparer(Of TKey))
Parametrar
- comparer
- IEqualityComparer<TKey>
Implementeringen IEqualityComparer<T> som ska användas vid jämförelse av nycklar eller null för att använda standardvärdet EqualityComparer<T> för typen av nyckel.
Exempel
I följande kodexempel skapas en Dictionary<TKey,TValue> med en skiftlägesokänslig likhetsjämförelse för den aktuella kulturen. Exemplet lägger till fyra element, vissa med gemener och några med versaler. Exemplet försöker sedan lägga till ett element med en nyckel som endast skiljer sig från en befintlig nyckel från fall till fall, fångar det resulterande undantaget och visar ett felmeddelande. Slutligen visar exemplet elementen i ordlistan.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new Dictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
Dictionary<string, string> openWith =
new Dictionary<string, string>(
StringComparer.CurrentCultureIgnoreCase);
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("DIB", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
{
openWith.Add("BMP", "paint.exe");
}
catch (ArgumentException)
{
Console.WriteLine("\nBMP is already in the dictionary.");
}
// List the contents of the sorted dictionary.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
kvp.Value);
}
}
}
/* This code example produces the following output:
BMP is already in the dictionary.
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
*/
open System
open System.Collections.Generic
// Create a new Dictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
let openWith = Dictionary<string, string> StringComparer.CurrentCultureIgnoreCase
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
openWith.Add("BMP", "paint.exe")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the sorted dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// BMP is already in the dictionary.
//
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new Dictionary of strings, with string keys
' and a case-insensitive comparer for the current culture.
Dim openWith As New Dictionary(Of String, String)( _
StringComparer.CurrentCultureIgnoreCase)
' Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Try to add a fifth element with a key that is the same
' except for case; this would be allowed with the default
' comparer.
Try
openWith.Add("BMP", "paint.exe")
Catch ex As ArgumentException
Console.WriteLine(vbLf & "BMP is already in the dictionary.")
End Try
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
Kommentarer
Använd den här konstruktorn med skiftlägesokänsliga strängjäxorer som tillhandahålls av StringComparer klassen för att skapa ordlistor med skiftlägesokänsliga strängnycklar.
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt den angivna jämförelsen.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Om comparer är nullanvänder den här konstruktorn standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen.
Note
Om du kan uppskatta samlingens storlek eliminerar en konstruktor som anger den initiala kapaciteten behovet av att utföra ett antal storleksändringsåtgärder samtidigt som element läggs till i Dictionary<TKey,TValue>.
Den här konstruktorn är en O(1)-åtgärd.
Caution
Om capacity det kommer från användarindata föredrar du att använda en konstruktor utan en kapacitetsparameter och låta samlingen ändra storlek när element läggs till. Om du måste använda ett användarangivet värde kan du antingen klämma fast det till en rimlig gräns (till exempel Math.Clamp(untrustedValue, 0, 20)) eller kontrollera att elementantalet matchar det angivna värdet.
Se även
Gäller för
Dictionary<TKey,TValue>(Int32)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har den angivna initiala kapaciteten och använder standardjämförlikningsjämföraren för nyckeltypen.
public:
Dictionary(int capacity);
public Dictionary(int capacity);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer)
Parametrar
- capacity
- Int32
Det inledande antalet element som Dictionary<TKey,TValue> kan innehålla.
Undantag
capacity är mindre än 0.
Exempel
I följande kodexempel skapas en ordlista med en initial kapacitet på 4 och fyller den med 4 poster.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys and
// an initial capacity of 4.
Dictionary<string, string> openWith =
new Dictionary<string, string>(4);
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// List the contents of the dictionary.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
}
}
/* This code example produces the following output:
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
*/
open System.Collections.Generic
// Create a new dictionary of strings, with string keys and
// an initial capacity of 4.
let openWith = Dictionary<string, string> 4
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = dib, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys and
' an initial capacity of 4.
Dim openWith As New Dictionary(Of String, String)(4)
' Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
Kommentarer
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt standardjämförlikningsjämföraren.
Kapaciteten för en Dictionary<TKey,TValue> är antalet element som kan läggas till Dictionary<TKey,TValue> i innan storleksändring krävs. När element läggs till i en Dictionary<TKey,TValue>ökas kapaciteten automatiskt efter behov genom att den interna matrisen omplaceras.
Om storleken på samlingen kan uppskattas eliminerar du behovet av att utföra ett antal storleksändringsåtgärder när du lägger till element i Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Den här konstruktorn använder standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen. Du kan också ange en implementering av det IEqualityComparer<T> allmänna gränssnittet med hjälp av en konstruktor som accepterar en comparer parameter.
Den här konstruktorn är en O(1)-åtgärd.
Caution
Om capacity det kommer från användarindata föredrar du att använda en konstruktor utan en kapacitetsparameter och låta samlingen ändra storlek när element läggs till. Om du måste använda ett användarangivet värde kan du antingen klämma fast det till en rimlig gräns (till exempel Math.Clamp(untrustedValue, 0, 20)) eller kontrollera att elementantalet matchar det angivna värdet.
Se även
Gäller för
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IDictionary<TKey,TValue> och använder den angivna IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IEqualityComparer(Of TKey))
Parametrar
- dictionary
- IDictionary<TKey,TValue>
Vars IDictionary<TKey,TValue> element kopieras till den nya Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Implementeringen IEqualityComparer<T> som ska användas vid jämförelse av nycklar eller null för att använda standardvärdet EqualityComparer<T> för typen av nyckel.
Undantag
dictionary är null.
dictionary innehåller en eller flera dubblettnycklar.
Exempel
Följande kodexempel visar hur du använder Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktorn för att initiera ett Dictionary<TKey,TValue> med skiftlägesokänsligt sorterat innehåll från en annan ordlista. Kodexemplet skapar en SortedDictionary<TKey,TValue> med en skiftlägesokänslig jämförelse och fyller den med data i slumpmässig ordning och skickar SortedDictionary<TKey,TValue> sedan till Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktorn, tillsammans med en skiftlägesokänslig likhetsjämförare, vilket skapar en Dictionary<TKey,TValue> som sorteras. Det här är användbart om du behöver skapa en sorterad ordlista som någon gång blir statisk. att kopiera data från en SortedDictionary<TKey,TValue> till en Dictionary<TKey,TValue> förbättrar hämtningshastigheten.
Note
När du skapar en ny ordlista med en skiftlägeskänslig jämförelse och fyller den med poster från en ordlista som använder en skiftlägeskänslig jämförelse, som i det här exemplet, uppstår ett undantag om indataordlistan har nycklar som endast skiljer sig åt från fall till fall.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new sorted dictionary of strings, with string
// keys and a case-insensitive comparer.
SortedDictionary<string, string> openWith =
new SortedDictionary<string, string>(
StringComparer.CurrentCultureIgnoreCase);
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe");
openWith.Add("Bmp", "paint.exe");
openWith.Add("DIB", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// Create a Dictionary of strings with string keys and a
// case-insensitive equality comparer, and initialize it
// with the contents of the sorted dictionary.
Dictionary<string, string> copy =
new Dictionary<string, string>(openWith,
StringComparer.CurrentCultureIgnoreCase);
// List the contents of the copy.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in copy )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
}
}
/* This code example produces the following output:
Key = Bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
*/
open System
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys and a case-insensitive comparer.
let openWith =
SortedDictionary<string, string> StringComparer.CurrentCultureIgnoreCase
// Add some elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("Bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Create a Dictionary of strings with string keys and a
// case-insensitive equality comparer, and initialize it
// with the contents of the sorted dictionary.
let copy =
Dictionary<string, string>(openWith, StringComparer.CurrentCultureIgnoreCase)
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// Key = Bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
// Key = txt, Value = notepad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new sorted dictionary of strings, with string
' keys and a case-insensitive comparer.
Dim openWith As New SortedDictionary(Of String, String)( _
StringComparer.CurrentCultureIgnoreCase)
' Add some elements to the sorted dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("Bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Create a Dictionary of strings with string keys and a
' case-insensitive equality comparer, and initialize it
' with the contents of the sorted dictionary.
Dim copy As New Dictionary(Of String, String)(openWith, _
StringComparer.CurrentCultureIgnoreCase)
' List the contents of the copy.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In copy
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
Kommentarer
Använd den här konstruktorn med skiftlägesokänsliga strängjäxorer som tillhandahålls av StringComparer klassen för att skapa ordlistor med skiftlägesokänsliga strängnycklar.
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt den angivna jämförelsen. På samma sätt måste varje nyckel i källan dictionary också vara unik enligt den angivna jämförelsen.
Note
Dubblettnycklar kan till exempel inträffa om comparer är en av de skiftlägeskänsliga strängjäxor som tillhandahålls av StringComparer klassen och dictionary inte använder en skiftlägeskänslig jämförelsenyckel.
Den ursprungliga kapaciteten för den nya Dictionary<TKey,TValue> är tillräckligt stor för att innehålla alla element i dictionary.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Om comparer är nullanvänder den här konstruktorn standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen.
Den här konstruktorn är en O(n)-åtgärd, där n är antalet element i dictionary.
Se även
Gäller för
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som innehåller element som kopierats från den angivna IEnumerable<T> och använder den angivna IEqualityComparer<T>.
public:
Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)), comparer As IEqualityComparer(Of TKey))
Parametrar
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Vars IEnumerable<T> element kopieras till den nya Dictionary<TKey,TValue>.
- comparer
- IEqualityComparer<TKey>
Implementeringen IEqualityComparer<T> som ska användas vid jämförelse av nycklar eller null för att använda standardvärdet EqualityComparer<T> för typen av nyckel.
Undantag
collection är null.
collection innehåller en eller flera duplicerade nycklar.
Gäller för
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)
Initierar en ny instans av Dictionary<TKey,TValue> klassen som är tom, har den angivna initiala kapaciteten och använder den angivna IEqualityComparer<T>.
public:
Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of TKey))
Parametrar
- capacity
- Int32
Det inledande antalet element som Dictionary<TKey,TValue> kan innehålla.
- comparer
- IEqualityComparer<TKey>
Implementeringen IEqualityComparer<T> som ska användas vid jämförelse av nycklar eller null för att använda standardvärdet EqualityComparer<T> för typen av nyckel.
Undantag
capacity är mindre än 0.
Exempel
I följande kodexempel skapas en Dictionary<TKey,TValue> med en initial kapacitet på 5 och en skiftlägeskänslig likhetsjämförelse för den aktuella kulturen. Exemplet lägger till fyra element, vissa med gemener och några med versaler. Exemplet försöker sedan lägga till ett element med en nyckel som endast skiljer sig från en befintlig nyckel från fall till fall, fångar det resulterande undantaget och visar ett felmeddelande. Slutligen visar exemplet elementen i ordlistan.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys, an
// initial capacity of 5, and a case-insensitive equality
// comparer.
Dictionary<string, string> openWith =
new Dictionary<string, string>(5,
StringComparer.CurrentCultureIgnoreCase);
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("DIB", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
{
openWith.Add("BMP", "paint.exe");
}
catch (ArgumentException)
{
Console.WriteLine("\nBMP is already in the dictionary.");
}
// List the contents of the dictionary.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key,
kvp.Value);
}
}
}
/* This code example produces the following output:
BMP is already in the dictionary.
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
*/
open System
open System.Collections.Generic
// Create a new dictionary of strings, with string keys, an
// initial capacity of 5, and a case-insensitive equality
// comparer.
let openWith =
Dictionary<string, string>(5, StringComparer.CurrentCultureIgnoreCase)
// Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
// Try to add a fifth element with a key that is the same
// except for case; this would be allowed with the default
// comparer.
try
openWith.Add("BMP", "paint.exe")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// This code example produces the following output:
// BMP is already in the dictionary.
//
// Key = txt, Value = notepad.exe
// Key = bmp, Value = paint.exe
// Key = DIB, Value = paint.exe
// Key = rtf, Value = wordpad.exe
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new Dictionary of strings, with string keys, an
' initial capacity of 5, and a case-insensitive equality
' comparer.
Dim openWith As New Dictionary(Of String, String)(5, _
StringComparer.CurrentCultureIgnoreCase)
' Add 4 elements to the dictionary.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("DIB", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
' Try to add a fifth element with a key that is the same
' except for case; this would be allowed with the default
' comparer.
Try
openWith.Add("BMP", "paint.exe")
Catch ex As ArgumentException
Console.WriteLine(vbLf & "BMP is already in the dictionary.")
End Try
' List the contents of the dictionary.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
End Sub
End Class
' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
Kommentarer
Använd den här konstruktorn med skiftlägesokänsliga strängjäxorer som tillhandahålls av StringComparer klassen för att skapa ordlistor med skiftlägesokänsliga strängnycklar.
Varje nyckel i en Dictionary<TKey,TValue> måste vara unik enligt den angivna jämförelsen.
Kapaciteten för en Dictionary<TKey,TValue> är antalet element som kan läggas till Dictionary<TKey,TValue> i innan storleksändring krävs. När element läggs till i en Dictionary<TKey,TValue>ökas kapaciteten automatiskt efter behov genom att den interna matrisen omplaceras.
Om storleken på samlingen kan uppskattas eliminerar du behovet av att utföra ett antal storleksändringsåtgärder när du lägger till element i Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> kräver en likhetsimplementering för att avgöra om nycklarna är lika. Om comparer är nullanvänder den här konstruktorn standardjämförelsen för allmän likhet, EqualityComparer<T>.Default. Om typen TKey implementerar det System.IEquatable<T> allmänna gränssnittet använder standardjämförlikningsjämföraren den implementeringen.
Den här konstruktorn är en O(1)-åtgärd.
Se även
Gäller för
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
Initierar en ny instans av Dictionary<TKey,TValue> klassen med serialiserade data.
protected:
Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
Protected Sub New (info As SerializationInfo, context As StreamingContext)
Parametrar
- info
- SerializationInfo
Ett SerializationInfo objekt som innehåller den information som krävs för att serialisera Dictionary<TKey,TValue>.
- context
- StreamingContext
En StreamingContext struktur som innehåller källan och målet för den serialiserade dataström som är associerad med Dictionary<TKey,TValue>.
Kommentarer
Den här konstruktorn anropas under deserialiseringen för att återskapa ett objekt som överförs via en ström. Mer information finns i XML- och SOAP-serialisering.