当前位置:网站首页>Example of dictionary
Example of dictionary
2022-07-24 07:45:00 【Glunn】
Dictionary Dictionaries
Must contain a namespace System.Collection.Generic
Dictionary Every element in it is a key value pair ( It's made up of two elements : Key and value )
The key must be unique , And values don't need to be unique
Keys and values can be of any type ( such as :string, int, Custom type , wait )
The time to read a value through a key is close to O(1)
The partial order between key value pairs can not be defined
// Definition
Dictionary<string, string> openWith = new Dictionary<string, string>();
// Additive elements
openWith.Add(“txt”, “notepad.exe”);
openWith.Add(“bmp”, “paint.exe”);
openWith.Add(“dib”, “paint.exe”);
openWith.Add(“rtf”, “wordpad.exe”);
// Value
Console.WriteLine(“For key = “rtf”, value = {0}.”, openWith[“rtf”]);
// Change value
openWith[“rtf”] = “winword.exe”;
Console.WriteLine(“For key = “rtf”, value = {0}.”, openWith[“rtf”]);
// Traverse key
foreach (string key in openWith.Keys)
{
Console.WriteLine(“Key = {0}”, key);
}
// Traverse value
foreach (string value in openWith.Values)
{
Console.WriteLine("value = {0}", value);
}
// Traverse value, Second Method
Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
foreach (string s in valueColl)
{
Console.WriteLine("Second Method, Value = {0}", s);
}
// Ergodic dictionary
foreach (KeyValuePair<string, string> kvp in openWith)
{
Console.WriteLine(“Key = {0}, Value = {1}”, kvp.Key, kvp.Value);
}
// Add existing elements
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// Remove elements
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
// The judgment key exists
if (openWith.ContainsKey(“bmp”)) // True {
Console.WriteLine(“An element with Key = “bmp” exists.”);
}
The parameter is a custom type
First define the class
class DouCube
{
public int Code { get { return _Code; } set { _Code = value; } } private int _Code;
public string Page { get { return _Page; } set { _Page = value; } } private string _Page;
}
then
// Declare and add elements
Dictionary<int, DouCube> MyType = new Dictionary<int, DouCube>();
for (int i = 1; i <= 9; i++)
{
DouCube element = new DouCube();
element.Code = i * 100;
element.Page = "http://www.doucube.com/" + i.ToString() + ".html";
MyType.Add(i, element);
}
// Traversing elements
foreach (KeyValuePair<int, DouCube> kvp in MyType)
{
Console.WriteLine("Index {0} Code:{1} Page:{2}", kvp.Key, kvp.Value.Code, kvp.Value.Page);
}
Common properties
name explain
Comparer Gets the parameter used to determine whether the keys in the dictionary are equal IEqualityComparer.
Count Get included in Dictionary<TKey, TValue> The key / The right number .
Item Gets or sets the value associated with the specified key .
Keys Get contains Dictionary<TKey, TValue> The set of keys in .
Values Get contains Dictionary<TKey, TValue> The set of values in .
Common methods
name explain
Add Adds the specified key and value to the dictionary .
Clear from Dictionary<TKey, TValue> Remove all keys and values from .
ContainsKey determine Dictionary<TKey, TValue> Whether to include the specified key .
ContainsValue determine Dictionary<TKey, TValue> Whether to include a specific value .
Equals(Object) Determine the specified Object Is it equal to the current Object. ( Inherited from Object.)
Finalize Allow objects in “ Garbage collection ” Attempt to free resources and perform other cleanup operations before recycling . ( Inherited from Object.)
GetEnumerator Return to loop access Dictionary<TKey, TValue> The enumerator of .
GetHashCode Used as a hash function of a specific type . ( Inherited from Object.)
GetObjectData Realization System.Runtime.Serialization.ISerializable Interface , And return serialization Dictionary<TKey, TValue> Data required by the instance .
GetType Get the current instance's Type. ( Inherited from Object.)
MemberwiseClone Create current Object Shallow copy of . ( Inherited from Object.)
OnDeserialization Realization System.Runtime.Serialization.ISerializable Interface , And raise the deserialization event after deserialization .
Remove from Dictionary<TKey, TValue> Remove the value of the specified key from the .
ToString Returns a string representing the current object . ( Inherited from Object.)
TryGetValue Gets the value associated with the specified key .
using System;
using System.Collections.Generic;// Collections and containers of generic namespaces system.collection.generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication39
{
class Program
{
enum enum1
{ Monday , Tuesday , Wednesday , Thursday , Friday };
static void Main(string[] args)
{
Dictionary<string,int> zidian=new Dictionary<string,int>();// Defines a dictionary , Inside pass key The type of value and the type of value to be passed in
zidian.Add(“ A no. ”,45);
zidian.Add(“ Number two ”,43);
int count=zidian[“ Number two ”];
Console.WriteLine(count);
bool boo = zidian.ContainsKey(“ A no. ”);// Whether to include this key
Console.WriteLine(boo);
boo = zidian.ContainsValue(40);// Whether to include this value
Console.WriteLine(boo);
//zidian.Clear();// Clear the dictionary
//zidian.Remove()// Remove the position of the specified key
int a = 0;
zidian.TryGetValue(“ A no. ”,out a);// Assign the value in key one to a
int c=zidian.Count();// View the contents of the key ;
Console.WriteLine;
Console.WriteLine(a);
Dictionary<enum1, string> zidian2 = new Dictionary<enum1, string>();
zidian2.Add(enum1. Monday , “ Go to work ”);
zidian2.Add(enum1. Tuesday , “hsdf”);
Console.ReadKey();
}
}
}
边栏推荐
- JMeter stress test index interpretation
- Good programmers and bad programmers
- FlinkSQL-UDF自定义数据源
- Selenium basic knowledge automatic search
- Harbor2.2 用户角色权限速查
- Induction, generalization, deduction
- 多种优化方法打印100~200之间的素数
- 2021-06-03 database query - sorting
- 【Pytorch】conv2d torchvision.transforms
- [sklearn] RF cross validation out of bag data parameter learning curve grid search
猜你喜欢

Advanced part of C language IV. detailed explanation of user-defined types

Kali installing PIP and pip source changing

Problems encountered in inserting large quantities of data into the database in the project

Network security B module windows operating system penetration test of national vocational college skills competition

Mitre att & CK ultra detailed learning notes-01 (background, terms, cases)

【Pytorch】conv2d torchvision.transforms

Reptile learning - Overview

Selenium basic knowledge debugging method

C language advanced part VII. Program compilation and preprocessing

The solution of unable to import custom library in pycharm
随机推荐
Using bidirectional linked list to realize stack (c)
numpy.cumsum
One click Copy and import of web interface data into postman
多种优化方法打印100~200之间的素数
Implement a queue with two stacks.
Hcip day 9 notes
[sklearn] RF cross validation out of bag data parameter learning curve grid search
Sense dimension design responsive layout
Selenium basic knowledge automatically login Baidu online disk
【云原生】MySql索引分析及查询优化
Installation and use of Zen path & defect report & defect operation
Service Vulnerability & FTP & RDP & SSH & Rsync
Influxdb unauthorized access & CouchDB permission bypass
Stable TTL serial port rate supported by Arduino under different dominant frequencies
numpy.arange
Injectfix principle learning (to realize the heat of repair addition)
Introduction to C language II. Functions
Give a string ① please count the number of times each letter appears ② please print the pair with the most letters
服务漏洞&FTP&RDP&SSH&rsync
Movie recommendation system