在C#中,使用Dictionary類來管理由鍵值對組成的集合,這類集合稱為字典。
字典最大的特點就是能夠根據鍵來快速查找集合中的值。
下面是一個使用字典的小實例,希望通過這個小實例,能讓大家對字典操作有一個初步的了解。下面是完整代碼。
//************************************************************ // // Dictionary示例代碼 // // Author:三五月兒 //  // Date:2014/09/14 // // //************************************************************ using System;using System.Collections.Generic;using System.Linq;namespace DictionaryExp{  class Program  {    static void Main(string[] args)    {      //所有班級所有學生成績報告單      Dictionary<int, List<ScoreReport>> scoreDictionary = new Dictionary<int, List<ScoreReport>>();      //將1班所有學生成績加入字典      scoreDictionary.Add(1,        new List<ScoreReport>()        {          new ScoreReport(){Name="三五月兒",ChineseScore=100,MathScore=100,EnglishScore=100},          new ScoreReport(){Name="張三",ChineseScore=80,MathScore=78,EnglishScore=91},          new ScoreReport(){Name="李四",ChineseScore=90,MathScore=87,EnglishScore=88}        });      //將2班所有學生的成績加入字典      scoreDictionary.Add(2,        new List<ScoreReport>()        {          new ScoreReport(){Name="王五",ChineseScore=78,MathScore=88,EnglishScore=98},          new ScoreReport(){Name="丁六",ChineseScore=77,MathScore=99,EnglishScore=91},          new ScoreReport(){Name="魏源",ChineseScore=45,MathScore=66,EnglishScore=99}        });      //將3班所有學生的成績加入字典      scoreDictionary.Add(3,        new List<ScoreReport>()        {          new ScoreReport(){Name="周鵬",ChineseScore=99,MathScore=89,EnglishScore=78},          new ScoreReport(){Name="毛錢",ChineseScore=66,MathScore=98,EnglishScore=91},          new ScoreReport(){Name="皮蛋",ChineseScore=87,MathScore=69,EnglishScore=88}        });       //所有班級學生成績統計報告單      Dictionary<int, ScoreStatistics> scoreStatisticsDictionary = new Dictionary<int, ScoreStatistics>();      scoreStatisticsDictionary.Add(1, new ScoreStatistics());      scoreStatisticsDictionary.Add(2, new ScoreStatistics());      scoreStatisticsDictionary.Add(3, new ScoreStatistics());       //獲取班級Key的集合      Dictionary<int, List<ScoreReport>>.KeyCollection keyCollection = scoreDictionary.Keys;      //通過班級Key遍歷班級學生成績      foreach (var key in keyCollection)      {        //班級成績統計報告單中包含本班級時才繼續        if (scoreStatisticsDictionary.ContainsKey(key))        {          //當前班級所有學生的詳細成績報告單          List<ScoreReport> scoreList = new List<ScoreReport>();          scoreDictionary.TryGetValue(key, out scoreList);                    if (scoreList != null && scoreList.Count > 0)          {//當前班級所有學生的詳細成績報告單中存在數據            int count = scoreList.Count;//當前班級學生人數            //生成當前班級學生成績的統計報告單            ScoreStatistics scoreStatistics = new ScoreStatistics();            scoreStatisticsDictionary.TryGetValue(key, out scoreStatistics);            scoreStatistics.ClassId = key;            scoreStatistics.TotalChineseScore = scoreList.Sum(it => it.ChineseScore);            scoreStatistics.TotalMathScore = scoreList.Sum(it => it.MathScore);            scoreStatistics.TotalEnglishScore = scoreList.Sum(it => it.EnglishScore);            scoreStatistics.AverageChineseScore = scoreStatistics.TotalChineseScore / count;            scoreStatistics.AverageMathScore = scoreStatistics.TotalMathScore / count;            scoreStatistics.AverageEnglishScore = scoreStatistics.TotalEnglishScore / count;          }        }      }       foreach (var s in scoreStatisticsDictionary)      {        Console.WriteLine("ClassId = {0},TotalChineseScore = {1},TotalMathScore = {2},TotalEnglishScore = {3},AverageChineseScore = {4},AverageMathScore = {5},AverageEnglishScore = {6}",          s.Value.ClassId, s.Value.TotalChineseScore, s.Value.TotalMathScore, s.Value.TotalEnglishScore, s.Value.AverageChineseScore, s.Value.AverageMathScore, s.Value.AverageEnglishScore);        Console.WriteLine("-------------------------------------------------");      }    }  }  class ScoreReport  {    public string Name { get; set; }    public int ChineseScore { get; set; }    public int MathScore { get; set; }    public int EnglishScore { get; set; }  }   class ScoreStatistics  {    public int ClassId { get; set; }    public int TotalChineseScore { get; set; }    public int TotalMathScore { get; set; }    public int TotalEnglishScore { get; set; }    public int AverageChineseScore { get; set; }    public int AverageMathScore { get; set; }    public int AverageEnglishScore { get; set; }  }}實例中需要定義兩個類:
ScoreReport類表示單個學生的成績報告單,而ScoreStatistics類表示整個班級的成績統計報告單,統計信息包含班級各科成績的總分和平均分。
在程序的Main方法中:
首先,實例化字典對象,其中:
Dictionary<int, List<ScoreReport>>類型的字典scoreDictionary用來保存所有班級所有學生的詳細成績報告單,Key為班級Id,Value為List<ScoreReport>類型的集合,該集合保存班級所有學生的成績報告單。
Dictionary<int, ScoreStatistics>類型的字典scoreStatisticsDictionary用來保存所有班級的成績統計報告單,Key同樣為班級Id,Value為班級的成績統計報告單,使用ScoreStatistics類型的對象保存。
接著,向字典scoreDictionary與scoreStatisticsDictionary中分別加入三個班級的學生詳細成績報告單及班級成績統計報告單,此時scoreStatisticsDictionary中加入的班級成績統計報告單并不包含真實的統計信息,真實的統計信息需要在后面的計算過程中寫入。
最后,遍歷scoreDictionary字典,依次取出各個班級所有學生的成績信息并生成班級成績的統計信息寫入scoreDictionary字典并輸出,最終的運行效果如下圖所示:

圖1 程序運行效果圖
在我們的實例中使用到了Dictionary類的以下方法:
1、Add方法
使用Add方法將Key-Value對加入字典。
2、ContainsKey方法
使用ContainsKey方法可以確認字典中是否包含指定Key的鍵值對,若存在,返回true,否則返回false。
3、TryGetValue方法
使用TryGetValue方法獲取指定Key對應的Value。
另外,實例中還使用到了Dictionary類的Keys屬性,該屬性返回字典中所有Key的集合。
好了,就到這里了。
新聞熱點
疑難解答