zoukankan      html  css  js  c++  java
  • 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());
    }

  • 相关阅读:
    修复文件系统
    遗忘root密码,对密码进行重置
    grub引导程序破坏修复下
    模拟Grub引导故障上(配置文件损坏)
    模拟MBR故障修复
    RAID5 制作 (一个硬盘制作)
    RAID10 (硬盘制作)
    du,df区别
    07_软件的安装
    06_find-查找文件
  • 原文地址:https://www.cnblogs.com/xxaxx/p/2395806.html
Copyright © 2011-2022 走看看