C# Dictionary 用法;

定义一个数组LonLat[] arr = new LonLat[2];可不可以将这个数组使用Dictionary,将键和键值关联起来,比如
Dictionary<int, LonLat[]>;LonLat是自定义的结构体?
C# 帮助中Dictionary<TKey, TValue>,Tvalue是值类型,数组算不算值类型?求详细解答

C# Dictionary用法总结

1、用法1: 常规用

  增加键值对之前需要判断是否存在该键,如果已经存在该键而且不判断,将抛出异常。所以这样每次都要进行判断,很麻烦,在备注里使用了一个扩展方法

public static void DicSample1()
{
 
    Dictionary<String, String> pList = new Dictionary<String, String>();
    try
    {
        if (pList.ContainsKey("Item1") == false)
        {
            pList.Add("Item1", "ZheJiang");
        }
        if (pList.ContainsKey("Item2")== false)
        {
            pList.Add("Item2", "ShangHai");
        }
        else
        {
            pList["Item2"] = "ShangHai";
        }
        if (pList.ContainsKey("Item3") == false)
        {
            pList.Add("Item3", "BeiJiang");
        }
         
    }
    catch (System.Exception e)
    {
        Console.WriteLine("Error: {0}", e.Message);
    }
   
 
    //判断是否存在相应的key并显示
    if (pList.ContainsKey("Item1"))
    {
        Console.WriteLine("Output: " + pList["Item1"]);
    }
 
    //遍历Key
    foreach (var key in pList.Keys)
    {
        Console.WriteLine("Output Key: {0}", key);
    }
 
    //遍历Value
    foreach (String value in pList.Values)
    {
        Console.WriteLine("Output Value: {0}", value);
    }
    //遍历Key和Value
    foreach (var dic in pList)
    {
        Console.WriteLine("Output Key : {0}, Value : {1} ", dic.Key, dic.Value);
    }
} 

 

2、用法2:Dictionary的Value为一个数组

/// <summary>
/// Dictionary的Value为一个数组
/// </summary>
 public static void DicSample2()
 {
     Dictionary<String, String[]> dic = new Dictionary<String, String[]>();
     String[] ZheJiang =  { "Huzhou", "HangZhou", "TaiZhou" };
     String[] ShangHai = { "Budong", "Buxi" };
     dic.Add("ZJ", ZheJiang);
     dic.Add("SH", ShangHai);
     Console.WriteLine("Output :" + dic["ZJ"][0]);
 }

3、用法3: Dictionary的Value为一个类

//Dictionary的Value为一个类
public static void DicSample3()
 {
     Dictionary<String, Student> stuList = new Dictionary<String, Student>();
     Student stu = null;
     for (int i = 0; i < 3; i++ )
     {
         stu = new Student();
         stu.Name = i.ToString();
         stu.Name = "StuName" + i.ToString();
         stuList.Add(i.ToString(), stu);
     }
 
     foreach (var student in stuList)
     {
         Console.WriteLine("Output : Key {0}, Num : {1}, Name {2}", student.Key, student.Value.Name, student.Value.Name);
     }
 }
   
  
Student类:
public class Student
{
    public String Num { get; set; }
    public String Name { get; set; }
}

 4 备注:Dictionary的扩展方法使用

/// <summary>
/// Dictionary的扩展方法使用
/// </summary>
 public static void DicSample4()
 {
     //1)普通调用
     Dictionary<int, String> dict = new Dictionary<int, String>();
     DictionaryExtensionMethodClass.TryAdd(dict, 1, "ZhangSan");
     DictionaryExtensionMethodClass.TryAdd(dict, 2, "WangWu");
     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "WangWu");
     DictionaryExtensionMethodClass.AddOrPeplace(dict, 3, "ZhangWu");
     DictionaryExtensionMethodClass.TryAdd(dict, 2, "LiSi");
 
     //2)TryAdd å’Œ AddOrReplace è¿™ä¸¤ä¸ªæ–¹æ³•å…·æœ‰è¾ƒå¼ºè‡ªæˆ‘描述能力,用起来很省心,而且也简单:
     dict.AddOrPeplace(20, "Orange");
     dict.TryAdd(21, "Banana");
     dict.TryAdd(22, "apple");
 
     //3)像Linq或jQuery一样连起来写  
     dict.TryAdd(10, "Bob")
         .TryAdd(11, "Tom")
         .AddOrPeplace(12, "Jom");
 
     //4) èŽ·å–值
     String F = "Ba";
     dict.TryGetValue(31, out F);
     Console.WriteLine("F : {0}",F);
 
     foreach (var dic in dict)
     {
         Console.WriteLine("Output : Key : {0}, Value : {1}", dic.Key, dic.Value);
     }
     //5)下面是使用GetValue获取值
     var v1 = dict.GetValue(111,null);
     var v2 = dict.GetValue(10,"abc");
 
     //6)批量添加
     var dict1 = new Dictionary<int,int>();
     dict1.AddOrPeplace(3, 3);
     dict1.AddOrPeplace(5, 5);
 
     var dict2 = new Dictionary<int, int>();
     dict2.AddOrPeplace(1, 1);
     dict2.AddOrPeplace(4, 4);
     dict2.AddRange(dict1, false);
 }
   
  扩展方法所在的类
public static class DictionaryExtensionMethodClass
{
    /// <summary>
    /// å°è¯•å°†é”®å’Œå€¼æ·»åŠ åˆ°å­—典中:如果不存在,才添加;存在,不添加也不抛导常
    /// </summary>
    public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        if (dict.ContainsKey(key) == false)
            dict.Add(key, value);
        return dict;
    }
 
    /// <summary>
    /// å°†é”®å’Œå€¼æ·»åŠ æˆ–替换到字典中:如果不存在,则添加;存在,则替换
    /// </summary>
    public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        dict[key] = value;
        return dict;
    }
 
    /// <summary>
    /// èŽ·å–与指定的键相关联的值,如果没有则返回输入的默认值
    /// </summary>
    public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
    {
        return dict.ContainsKey(key)?dict[key] : defaultValue;
    }
 
    /// <summary>
    /// å‘字典中批量添加键值对
    /// </summary>
    /// <param name="replaceExisted">如果已存在,是否替换</param>
    public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
    {
        foreach (var item in values)
        {
            if (dict.ContainsKey(item.Key) == false || replaceExisted)
                dict[item.Key] = item.Value;
        }
        return dict;
    }
 
 
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-11-24
Dictionary表示一个字典集合。
可以实现通过键值查找、插入、删除一个键-值对的操作,这些如果用数组实现都非常麻烦。
Key就是键,value就是值,相当于字典里,单词和解释的对应关系。key是键所以不能重复。
第2个回答  2019-11-21
插入、删除一个键-值对的操作,这些如果用数组实现都非常麻烦。
key就是键,value就是值,相当于字典里dictionary表示一个字典集合。
可以实现通过键值查找
第3个回答  2014-07-04
我们用的比较多的非泛型集合类主要有 ArrayList类 和 HashTable类。我们经常用HashTable 来存储将要写入到数据库或者返回的信息,在这之间要不断的进行类型的转化,增加了系统装箱和拆箱的负担,如果我们操纵的数据类型相对确定的化 用 Dictionary<TKey,TValue> 集合类来存储数据就方便多了,例如我们需要在电子商务网站中存储用户的购物车信息( 商品名,对应的商品个数)时,完全可以用 Dictionary<string, int> 来存储购物车信息,而不需要任何的类型转化。

下面是简单的例子,包括声明,填充键值对,移除键值对,遍历键值对

Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");
//如果添加已经存在的键,add方法会抛出异常
try
{
myDic.Add("ddd","ddd");
}
catch (ArgumentException ex)
{
Console.WriteLine("此键已经存在:" + ex.Message);
}
//解决add()异常的方法是用ContainsKey()方法来判断键是否存在
if (!myDic.ContainsKey("ddd"))
{
myDic.Add("ddd", "ddd");
}
else
{
Console.WriteLine("此键已经存在:");

}

//而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常
myDic ["ddd"]="ddd";
myDic["eee"] = "555";

//使用索引器来取值时,如果键不存在就会引发异常
try
{
Console.WriteLine("不存在的键""fff""的键值为:" + myDic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine("没有找到键引发异常:" + ex.Message);
}
//解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
string value = "";
if (myDic.TryGetValue("fff", out value))
{
Console.WriteLine("不存在的键""fff""的键值为:" + value );
}
else
{
Console.WriteLine("没有找到对应键的键值");
}

//下面用foreach 来遍历键值对
//泛型结构体 用来存储健值对
foreach (KeyValuePair<string, string> kvp in myDic)
{
Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
}
//获取值得集合
foreach (string s in myDic.Values)
{
Console.WriteLine("value={0}", s);
}
//获取值得另一种方式
Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string s in values)
{
Console.WriteLine("value={0}", s);
}
常用的属性和方法如下: 常用属性
属性说明

Comparer
获取用于确定字典中的键是否相等的 IEqualityComparer。

Count
获取包含在 Dictionary中的键/值对的数目。

Item
获取或设置与指定的键相关联的值。

Keys
获取包含 Dictionary中的键的集合。

Values
获取包含 Dictionary中的值的集合。

常用的方法 方法说明
Add
将指定的键和值添加到字典中。

Clear
从 Dictionary中移除所有的键和值。

ContainsKey
确定 Dictionary是否包含指定的键。

ContainsValue
确定 Dictionary是否包含特定值。

Equals
已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。)

GetEnumerator
返回循环访问 Dictionary的枚举数。

GetHashCode
用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。)

GetObjectData
实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary实例所需的数据。

GetType
获取当前实例的 Type。 (从 Object 继承。)

OnDeserialization
实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。

ReferenceEquals
确定指定的 Object实例是否是相同的实例。 (从 Object 继承。)

Remove
从 Dictionary中移除所指定的键的值。

ToString
返回表示当前 Object的 String。 (从 Object 继承。)

TryGetValue
获取与指定的键相关联的值。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Test
{
class Program
{
static void Main(string[] args)
{
char[] chars = new char[] { 'a', 'b', 'c', 'a', 'b', 'c', 'c', 'd', 'd', 'e', 'c' };

//存储字符和字符个数
Dictionary<char, int> dic = new Dictionary<char, int>();

foreach (char c in chars)
{
if (dic.ContainsKey(c))
dic[c] += 1;
else
dic.Add(c, 1);
}

//排序
List<KeyValuePair<char, int>> list = new List<KeyValuePair<char, int>>();

foreach (KeyValuePair<char, int> p in dic)
{
int count = list.Count;
for (int i = 0; i < list.Count; i++)
{
if (p.Value > list[i].Value)
{
list.Insert(i, p);
break;
}
else
{
if (p.Value == list[i].Value)
{
if (p.Key < p.Key)
{
list.Insert(i, p);
break;
}
else
continue;
}
else
continue;
}
}
if (count == list.Count)
list.Add(p);
}

//显示字符
string s = "";
foreach (KeyValuePair<char, int> p in list)
{
s += new string(p.Key, p.Value);
}
Console.WriteLine(s);
Console.Read();
}
}
}
摘自csdn 希望能帮助你
相似回答