C#中Dictionary类使用实例

 更新时间:2015年06月17日 10:29:12   投稿:junjie  
这篇文章主要介绍了C#中Dictionary类使用实例,本文直接给出一个使用实例,包含一些Dictionary的基本用法,需要的朋友可以参考下

在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的集合。

好了,就到这里了。

相关文章

  • C#调用存储过程详解(带返回值、参数输入输出等)

    C#调用存储过程详解(带返回值、参数输入输出等)

    这篇文章主要介绍了C#调用存储过程的方法,结合实例形式详细分析了各种常用的存储过程调用方法,包括带返回值、参数输入输出等,需要的朋友可以参考下
    2016-06-06
  • C#实现简单的Login窗口实例

    C#实现简单的Login窗口实例

    这篇文章主要介绍了C#实现简单的Login窗口,实例分析了C#显示及关闭登陆Login窗口的技巧,非常具有实用价值,需要的朋友可以参考下
    2015-08-08
  • C#8 的模式匹配实现

    C#8 的模式匹配实现

    这篇文章主要介绍了C#8 的模式匹配实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • SMTP客户端未通过身份验证等多种错误解决方案分享

    SMTP客户端未通过身份验证等多种错误解决方案分享

    这篇文章主要介绍了SMTP服务器要求安全连接或客户端未通过身份验证的多种解决方案,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • C#中如何将MongoDB->RunCommand结果映射到业务类的方法总结

    C#中如何将MongoDB->RunCommand结果映射到业务类的方法总结

    这篇文章主要给大家总结介绍了关于C#中如何将MongoDB->RunCommand结果映射到业务类的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2018-04-04
  • C#操作ftp类完整实例

    C#操作ftp类完整实例

    这篇文章主要介绍了C#操作ftp类,以一个完整实例形式详细分析了C#操作FTP文件传输所涉及的FTP连接、文件传输、参数设置、文件删除等技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • C#数组排序的两种常用方法

    C#数组排序的两种常用方法

    这篇文章主要介绍了C#数组排序的两种常用方法,实例分析了C#操作数组的相关技巧,需要的朋友可以参考下
    2015-05-05
  • WPF实现类似ChatGPT逐字打印效果的示例代码

    WPF实现类似ChatGPT逐字打印效果的示例代码

    前一段时间ChatGPT类的应用十分火爆,这类应用在回答用户的问题时逐字打印输出,像极了真人打字回复消息,本文就来利用WPF模拟一下这种逐字打印的效果吧
    2023-08-08
  • C#采用OpenXml给word里面插入图片

    C#采用OpenXml给word里面插入图片

    这篇文章主要介绍了C#采用OpenXml给word里面插入图片的方法,参考了MSDN官网的示例加以说明,是OpenXml操作Word的一个非常重要的应用,需要的朋友可以参考下
    2014-09-09
  • LZW压缩算法 C#源码

    LZW压缩算法 C#源码

    本文分享了一个LZW压缩算法的C#源码,有需要的朋友可以参考一下。
    2016-06-06

最新评论