Dictionary<int, Dictionary<string, string>> dict1 = new Dictionary<int, Dictionary<string, string>>();
Dictionary<int, Dictionary<string, string>> dict2 = new Dictionary<int, Dictionary<string, string>>();
Dictionary<string, string> _dict3 = new Dictionary<string, string>() { { "kkds", "wewer" }, { "ddd", "eeeeer" } };
Dictionary<string, string> _dict4 = new Dictionary<string, string>() { { "ccc", "rrrr" }, { "yyy", "uuuu" } };
Dictionary求符合某些特征的key或者value的值的和,用linq處理方法參考:
- private string ReturnDMY_Money(Dictionary<int, string> dic, string i)
- {
- var r = dic.Sum(x => x.Value.Split('|')[1] == i ? int.Parse(x.Value.Split('|')[0]) : 0);
- return r.ToString();
- }
C#2.0泛型詳細介紹
泛型是 C#2.0 語言和公共語言運行庫 (CLR) 中的一個新功能。泛型將類型參數的概念引入 .NET Framework,類型參數使得設計如下類和方法成為可能:這些類和方法將一個或多個類型的指定推遲到客戶端代碼聲明並實例化該類或方法的時候。例如, 通過使用泛型類型參數 T,可以編寫其他客戶端代碼能夠使用的單個類,而不致引入運行時強制轉換或裝箱操作.
使用泛型類型可以最大限度地重用代碼、保護類型的安全以及提高性能。
泛型最常見的用途是創建集合類。
.NET Framework 類庫在 System.Collections.Generic 命名空間中包含幾個新的泛型集合類。應盡可能地使用這些類來代替普通的類,如 System.Collections 命名空間中的 ArrayList,HashTable等。
非泛型類(System.Collections) | 對應的泛型類(System.Collections.Generic) |
ArrayList | List |
Hashtable | Dictionary |
Queue | Queue |
Stack | Stack |
SortedList | SortedList |
使用泛型的建議:
1.如果需要對多種類型進行相同的操作處理,則應該使用泛型。
2。如果需要處理值類型,則使用泛型可以避免裝箱拆箱帶來的性能開銷。
3.使用泛型可以在應用程序編譯時發現類型錯誤,增強程序的健壯性。
4.減少不必要的重復編碼,使代碼結構更加清晰。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//使用List<T>替換ArrayList
List<string> ls = new List<string>();
ls.Add("泛型集合元素1");
ls.Add("泛型集合元素2");
ls.Add("泛型集合元素3");
foreach (string s in ls)
Console.WriteLine(s);
//使用Dictionary<Tkey,Tvalue>
Console.WriteLine("Dictinary泛型集合類舉例");
Dictionary<string, string> dct = new Dictionary<string, string>();
dct.Add("鍵1", "值1");
dct.Add("鍵2", "值2");
dct.Add("鍵3", "值3");
foreach (KeyValuePair<string, string> kvp in dct)
Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
//使用Queue<T>
Console.WriteLine("Queue泛型集合類型:");
Queue<string> que = new Queue<string>();
que.Enqueue("這是隊列元素值1");
que.Enqueue("這是隊列元素值2");
foreach (string s in que)
Console.WriteLine(s);
//使用Stack<T>
Console.WriteLine("Stack泛型集合類舉例");
Stack<string> stack = new Stack<string>();
stack.Push("這是堆棧元素1");
stack.Push("這是堆棧元素2");
foreach (string s in stack)
Console.WriteLine(s);
//使用SortedList<Tkey,Tvalue>
Console.WriteLine("SortedList泛型集合舉例");
SortedList<string, string> sl = new SortedList<string, string>();
sl.Add("key1", "value1");
sl.Add("key2", "value2");
sl.Add("key3", "value3");
sl.Add("key4", "value4");
foreach (KeyValuePair<string, string> kvp in sl)
Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
Console.ReadLine();
}
}
}
下面我們就來說下,幾個泛型集合類的用法:
一.Dictionary
此類在 .NET Framework 2.0 版中是新增的。表示鍵和值的集合。命名空間:System.Collections.Generic,程序集:mscorlib(在 mscorlib.dll 中)
class TestGenericList
{
static void Main()
{
//聲明對象,參數表示,鍵是int類型,值是string類型
Dictionary<int, string> fruit = new Dictionary<int, string>();
try{
//加入重復鍵會引發異常
fruit.Add(1, "蘋果");
fruit.Add(2, "桔子");
fruit.Add(3, "香蕉");
fruit.Add(4, "菠蘿");
//參數錯誤將引發異常,如下所示
//fruit.Add("5", "aa");
}
catch (ArgumentException)
{
Console.WriteLine("添加錯誤!!!");
}
//因為引入了泛型,所以鍵取出后不需要進行Object到int的轉換,值的集合也一樣
foreach (int i in fruit.Keys)
{
Console.WriteLine("鍵是:{0} 值是:{1}",i,fruit);
}
//刪除指定鍵,值
fruit.Remove(1);
//判斷是否包含指定鍵
if (fruit.ContainsKey(1))
{
Console.WriteLine("包含此鍵");
}
//清除集合中所有對象
fruit.Clear();
}
}
Dictionary遍歷輸出的順序,就是加入的順序,這點與Hashtable不同,其它方法如:ContainsKey ,ContainsValue ,Remove 等,使用方法基本一致。
二、List類
注意:此類在 .NET Framework 2.0 版中是新增的。表示可通過索引訪問的對象的強類型列表。提供用於對列表進行搜索、排序和操作的方法。命名空 間:System.Collections.Generic,程序集:mscorlib(在 mscorlib.dll 中),List 類是 ArrayList 類的泛型等效類。
//聲明一個泛型類
class TestGenericList
{
static void Main()
{
//聲明一個List對象,只加入string參數
List<string> names = new List<string>();
names.Add("喬峰");
names.Add("歐陽峰");
names.Add("馬蜂");
//遍歷List
foreach (string name in names)
{
Console.WriteLine(name);
}
//向List中插入元素
names.Insert(2, "張三峰");
//移除指定元素
names.Remove("馬蜂");
}
}
在 決定使用 List 還是使用 ArrayList 類(兩者具有類似的功能)時,記住 List 類在大多數情況下執行得更好並且是類型安全的。如果對 List 類的類型 T 使用引用類型,則兩個類的行為是完全相同的。但是,如果對類型 T 使用值類型,則需要考慮實現和裝箱問題。
如果對類型 T 使用值類型,則編譯器將特別針對該值類型生成 List 類的實現。這意味着不必對 List 對象的列表元素進行裝箱就可以使用該元素,並且在創建大約 500 個列表元素之后,不對列表元素裝箱所節省的內存將大於生成該類實現所使用的內存。
其實我們也可以自己定義一個泛型類,如下所示:
//聲明一個泛型類
public class ItemList<T>
{
void Add(T item) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// 聲明一個對象,只能加入int型
ItemList<int> list1 = new ItemList<int>();
//聲明一個對象,只能加入Student類型,Student類為自定義類
ItemList<Student> list2 = new ItemList<Student>();
}
}
泛型的用法還有很多種,如泛型方法,泛型委托,泛型接口等。
泛型,就是說這個容器內只能裝 <>里面的類型。
List <String>中List中裝的是String
List <List <String>>中裝的是List
以前的List,好比是個箱子,你可以把相近的東西扔在里面
泛型好比是個收納箱,不但可以放對象,還要在上面標明箱子里面放什么東西
泛形的使用,因為list中的元素添加的是String類型的,使用泛形代表你list中所有元素都為String類型
說白了..就是LIST里再嵌套LIST...
<>使用了泛型,就是告訴JVM該LIST里面裝的是什么類型的東西.
List <String>中List中裝的是String
List <List <String>>中裝的是List,里面的LIST裝的是String.
恩恩,就是泛型沒錯啊,聲明數組的時候, <>里面寫的就是規定好了的數據類型或類,如:List <String>就表示這個里面只能裝String類型的東東,裝不進其他的,至於List <List <String>>嘛,就是,先來一個裝String類型的List,就是里面那個,再來一個裝List的List,就是外面那 個,Over!
用泛型的好處是顯而易見的性能問題
先看看不用泛型的時候:
List list=new ArrayList();
//list.add();
//填充list
for(int i=0;i <list.size();i++){
User user=(User)list.get(i);
}
每次取出來的時候都要把Object強轉成User類型,據Sun的技術人員說,這樣會損失不少性能
用了泛型之后:
List <User> list=new ArrayList <User>();
//list.add();
//填充list
for(int i=0;i <list.size();i++){
User user = list.get(i);
}
代碼變得健壯了不說,而且性能的提高也是非常可觀的。
我們在開發中經常會用List<string>來保存一組字符串,比如下面這段代碼:





可是有時候,我們要從中獲取一個字符串,字符串的內容就是集合中的內容,但是要用逗號隔開,下面的辦法可以實現:
上面這條語句,返回的結果應該是下面這個樣子:

下面讓我們來做個反向工程,從string轉換成List<string>
List<string> newStudentNames = new List<string>(result.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries));
foreach (string s in newStudentNames)
{
System.Diagnostics.Debug.WriteLine(s);
}
List<string> 定義強類型化string泛型 List<string> a = new List<string>();會有集合的許多操作,
List<>是一個泛型對象,實例化后相當於是一個List對象。List對象內部可以聚合若干個(理論上不限制大小)同類型對象,並提供很多方便的方法來提供一些基本操作。可以理解為一個封裝好的鏈表對象。
泛型本身的優點
1.類型安全
2.不用頻繁的的拆箱裝箱
string[] 就是簡單的強類型化數組.,沒什么好說的。
總的來說,List<>更靈活和方便使用,但是開銷更大。
Dictionary<string, string>是一個泛型使用說明
Posted on 2010-08-05 15:03 moss_tan_jun 閱讀(5653) 評論(0) 編輯 收藏
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)
{
Dictionary<int, string> dic = new Dictionary<int, string>();
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;
}
/// <summary>
/// 得到根據指定的Key行到Value
/// </summary>
protected void GetKeyValue()
{
Dictionary<string, int> myDictionary = SetKeyValue();
//測試得到公司2的值
int directorValue = myDictionary["公司2"];
Response.Write("公司2的value是:" + directorValue.ToString());
}