天天看點

C#中Dictionary的用法及用途

Dictionary<string, string>是一個泛型

他本身有集合的功能有時候可以把它看成數組

他的結構是這樣的:Dictionary<[key], [value]>

他的特點是存入對象是需要與[key]值一一對應的存入該泛型

通過某一個一定的[key]去找到對應的值

舉個例子:

//執行個體化對象

Dictionary<int, string> dic = new Dictionary<int, string>();

//對象打點添加

dic.Add(1, "one");

dic.Add(2, "two");

dic.Add(3, "one");

//提取元素的方法

string a = dic[1];

string b = dic[2];

string c = dic[3];

//1、2、3是鍵,分别對應“one”“two”“one”

//上面代碼中分别把值賦給了a,b,c

//注意,鍵相當于找到對應值的唯一辨別,是以不能重複

//但是值可以重複

如果你還看不懂我最後給你舉一個通俗的例子

有一缸米,你想在在每一粒上都刻上标記,不重複,相當于“鍵”當你找的時候一一對應不會找錯,這就是這個泛型的鍵的-作用,而米可以一樣,我的意思你明白了吧?

-------------------------------------------------------------------------

c# 對dictionary類進行排序用什麼接口實作

如果使用.Net Framework 3.5的話,事情就很簡單了。呵呵。

如果不是的話,還是自己寫排序吧。

using System;

using System.Collections.Generic;

using System.Text;

using System.Linq;

namespace DictionarySorting

{

class Program

static void Main(string[] args)

dic.Add(1, "HaHa");

dic.Add(5, "HoHo");

dic.Add(3, "HeHe");

dic.Add(2, "HiHi");

dic.Add(4, "HuHu");

var result = from pair in dic orderby pair.Key select pair;

foreach (KeyValuePair<int, string> pair in result)

Console.WriteLine("Key:{0}, Value:{1}", pair.Key, pair.Value);

}

Console.ReadKey();

【執行結果】

Key:1, Value:HaHa

Key:2, Value:HiHi

Key:3, Value:HeHe

Key:4, Value:HuHu

Key:5, Value:HoHo

Dictionary的基本用法。假如

需求:現在要導入一批資料,這些資料中有一個稱為公司的字段是我們資料庫裡已經存在了的,目前我們需要把每個公司名字轉為ID後才存入資料庫。

分析:每導一筆記錄的時候,就把要把公司的名字轉為公司的ID,這個不應該每次都查詢一下資料庫的,因為這太耗資料庫的性能了。

解決方案:在業務層裡先把所有的公司名稱及相應的公司ID一次性讀取出來,然後存放到一個Key和Value的鍵值對裡,然後實作隻要把一個公司的名字傳進去,就可以得到此公司相應的公司ID,就像查字典一樣。對,我們可以使用字典Dictionary操作這些資料。

示例:SetKeyValue()方法相應于從資料庫裡讀取到了公司資訊。

/// <summary>

/// 定義Key為string類型,Value為int類型的一個Dictionary

/// </summary>

/// <returns></returns>

protected Dictionary<string, int> SetKeyValue()

Dictionary<string, int> dic = new Dictionary<string, int>();

dic.Add("公司1", 1);

dic.Add("公司2", 2);

dic.Add("公司3", 3);

dic.Add("公司4", 4);

return dic;

/// 得到根據指定的Key行到Value

protected void GetKeyValue()

Dictionary<string, int> myDictionary = SetKeyValue();

//測試得到公司2的值

int directorValue = myDictionary["公司2"];

Response.Write("公司2的value是:" + directorValue.ToString());

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080858