zoukankan      html  css  js  c++  java
  • Dictionary用法详解

    1  Dictionary

    (1) 表示键和值的集合.

    (2)类型参数:

    TKey   字典中的键的类型

    TValue 字典中的值的类型

    (3)Dictionary 泛型类提供了从一组键到一组值的映射。字典中的每个添加项都由一个值及其相关联的键组成。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary 类是作为一个哈希表来实现的。

    (4)定义:

    Dictionary<string, string> openWith = new Dictionary<string, string>();

    (5)使用Add方法可以向其中添加值

    openWith.Add("txt", "notepad.exe");

    当添加重复的键时会引发ArgumentException类型的异常。

    (6)使用["txt"]的方法可以找到相对应的值,并可以修改这个键对应的值。

    如果键不存在,可以通过如下方法添加新的键/值对。

    openWith["doc"] = "winword.exe";

    如果取值的键不存在,会引发一个KeyNotFoundException类型的异常。

    (7)使用TryGetValue方法来尝试取出一个键对应的值,如果这个值存在就取出返回,这样可以避免抛出KeyNotFoundException异常。返回值类型为布尔类型。

    (8)使用ContainsKey方法来判断是否包含指定的键,返回值类型为布尔类型。

    (9)使用foreach遍历:

    foreach (KeyValuePair<string, string> kvp in openWith)
                {
                    Console.WriteLine("Key = {0}, Value = {1}",
                        kvp.Key, kvp.Value);
                }

    (10)使用Values属性,可以仅取出所有的值而不取出所有的键。

     Dictionary<string, string>.ValueCollection valuecol = openWith.Values;
    
    foreach (string str in valuecol)
          Console.WriteLine(str);

    (11)使用Keys属性,可以仅取出所有的键而不取出所有的值。

    (12)使用Remove方法,可以根据键来移除集合中的键/值对。

    openWith.Remove("jin");当移除值的时候同时移除键。

    2  实例程序

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
        public static void Main()
        {
            // 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.");
            }
    
            // The Item property is another name for the indexer, so you 
            // can omit its name when accessing elements. 
            Console.WriteLine("For key = \"rtf\", value = {0}.", 
                openWith["rtf"]);
    
            // The indexer can be used to change the value associated
            // with a key.
            openWith["rtf"] = "winword.exe";
            Console.WriteLine("For key = \"rtf\", value = {0}.", 
                openWith["rtf"]);
    
            // If a key does not exist, setting the indexer for that key
            // adds a new key/value pair.
            openWith["doc"] = "winword.exe";
    
            // The indexer throws an exception if the requested key is
            // not in the dictionary.
            try
            {
                Console.WriteLine("For key = \"tif\", value = {0}.", 
                    openWith["tif"]);
            }
            catch (KeyNotFoundException)
            {
                Console.WriteLine("Key = \"tif\" is not found.");
            }
    
            // When a program often has to try keys that turn out not to
            // be in the dictionary, TryGetValue can be a more efficient 
            // way to retrieve values.
            string value = "";
            if (openWith.TryGetValue("tif", out value))
            {
                Console.WriteLine("For key = \"tif\", value = {0}.", value);
            }
            else
            {
                Console.WriteLine("Key = \"tif\" is not found.");
            }
    
            // ContainsKey can be used to test keys before inserting 
            // them.
            if (!openWith.ContainsKey("ht"))
            {
                openWith.Add("ht", "hypertrm.exe");
                Console.WriteLine("Value added for key = \"ht\": {0}", 
                    openWith["ht"]);
            }
    
            // When you use foreach to enumerate dictionary elements,
            // the elements are retrieved as KeyValuePair objects.
            Console.WriteLine();
            foreach( KeyValuePair<string, string> kvp in openWith )
            {
                Console.WriteLine("Key = {0}, Value = {1}", 
                    kvp.Key, kvp.Value);
            }
    
            // To get the values alone, use the Values property.
            Dictionary<string, string>.ValueCollection valueColl =
                openWith.Values;
    
            // The elements of the ValueCollection are strongly typed
            // with the type that was specified for dictionary values.
            Console.WriteLine();
            foreach( string s in valueColl )
            {
                Console.WriteLine("Value = {0}", s);
            }
    
            // To get the keys alone, use the Keys property.
            Dictionary<string, string>.KeyCollection keyColl =
                openWith.Keys;
    
            // The elements of the KeyCollection are strongly typed
            // with the type that was specified for dictionary keys.
            Console.WriteLine();
            foreach( string s in keyColl )
            {
                Console.WriteLine("Key = {0}", s);
            }
    
            // Use the Remove method to remove a key/value pair.
            Console.WriteLine("\nRemove(\"doc\")");
            openWith.Remove("doc");
    
            if (!openWith.ContainsKey("doc"))
            {
                Console.WriteLine("Key \"doc\" is not found.");
            }
        }
    }
  • 相关阅读:
    Linux文件/proc/net/tcp分析
    为什么系统调用会消耗较多资源
    为什么Linux默认页大小是4KB
    为什么Linux需要虚拟内存
    Make 命令教程
    关于同步的一点思考-下
    关于同步的一点思考-上
    Linux下的进程控制块(PCB)
    汇编语言基础:寄存器和系统调用
    内核栈与thread_info结构详解
  • 原文地址:https://www.cnblogs.com/wang7/p/2506998.html
Copyright © 2011-2022 走看看