LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#中Dictionary的用法(取值/新增/编辑/删除/排序)及用途【Good!】

admin
2021年3月5日 11:35 本文热度 4247
Dictionary是一个泛型,他本身有集合的功能有时候可以把它看成数组,他的结构是这样的:
Dictionary<[key], [value]>
他的特点是存入对象是需要与[key]值一一对应的存入该泛型,通过某一个一定的[key]去找到对应的值。举个例子:
//实例化对象
Dictionary<int,string>dic=new Dictionary<int,string>();

//元素添加,要确保key还没有,否则会报错
dic.Add(1, "one");
dic.Add(2, "two");
dic.Add(3, "one");
//另外一种元素添加方法,无需判断key是否存在,无则新增,有则更新
dic[1]="one";
dic[2]="two";
dic[3]="one";

//提取元素的方法
string a = dic[1];
string b = dic[2];
string c = dic[3];
//1、2、3是键,分别对应“one”“two”“one”
//上面代码中分别把值赋给了a,b,c
//注意,键相当于找到对应值的唯一标识,所以不能重复
//但是值可以重复

//更新元素,其实和上面的新增是同一个,无需判断key是否存在,无则新增,有则更新
dic[1]="one";
dic[2]="two";
dic[3]="one";

更详细用法以 key 的类型为 int,value 的类型为 string 为例:
//创建及初始化
Dictionary<int,string>myDictionary=new Dictionary<int,string>();

//添加元素,要确保key还没有,否则会报错
myDictionary.Add(1,"C#");
myDictionary.Add(2,"C++");
myDictionary.Add(3,"ASP.NET");
myDictionary.Add(4,"MVC");
//另外一种元素添加方法,无需判断key是否存在,无则新增,有则更新
myDictionary[1]="C#";
myDictionary[2]="C++";
myDictionary[3]="ASP.NET";
myDictionary[4]="MVC";

//通过Key查找元素
if(myDictionary.ContainsKey(1))
{
      Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}

//通过KeyValuePair遍历元素
foreach(KeyValuePair kvp in myDictionary)
{
   Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}

//仅遍历键 Keys 属性
Dictionary.KeyCollection keyCol=myDictionary.Keys;
foreach(int key in keyCol)
{
    Console.WriteLine("Key = {0}", key);
}

//仅遍历值 Valus属性
Dictionary.ValueCollection valueCol=myDictionary.Values;
foreach(string value in valueCol)
{
     Console.WriteLine("Value = {0}", value);
}

//通过Remove方法移除指定的键值
myDictionary.Remove(1);
if(myDictionary.ContainsKey(1))
{
  Console.WriteLine("Key:{0},Value:{1}","1", myDictionary[1]);
}
else{
     Console.WriteLine("不存在 Key : 1");
}

//遍历key

foreach (string key in openWith.Keys)

{

    Console.WriteLine("Key = {0}", key);

}


//遍历value

foreach (string value in openWith.Values)

{

    Console.WriteLine("value = {0}", value);

}

 

//遍历value, Second Method

Dictionary<string, string>.ValueCollection valueColl = openWith.Values;

foreach (string s in valueColl)

{

    Console.WriteLine("Second Method, Value = {0}", s);

}


//遍历字典

foreach (KeyValuePair<string, string> kvp in openWith)

{

    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

}


//判断键存在

if (openWith.ContainsKey("bmp")) // True

{

    Console.WriteLine("An element with Key = \"bmp\" exists.");

}


参数为其他类型:

//参数为其它类型

Dictionary<int, string[]> OtherType = new Dictionary<int, string[]>();

OtherType.Add(1, "1,11,111".Split(','));

OtherType.Add(2, "2,22,222".Split(','));

Console.WriteLine(OtherType[1][2]);


几条建议:
1、给Dictionary添加元素时,建议直接用中括号的方式,而不是使用Add方法。
任何键key都必须是唯一的,不能添加相同key的键值,不然就会报错。虽然不管是用[]还是Add方法,调用的都是Dictionary的Insert函数,但是区别在于用Add函数的话,如果已经存在同样的键对值,会直接抛出ArgumentException,这意味着后续的代码都不执行了,这可很要命,明明是一个小问题,可看上去可能是一个大Bug。而用中括号属性的方法,如果不存在会添加,如果存在则进行改写,只要key值不为null,是不会抛出异常的。

2、利用TryGetValue(TKey key, out TValue value)接口获取Dictionary中的数据。
法一:ContainsKey(key) 方法:
if(myDictionary.ContainsKey(key))
{
    // 通过key索引value
    int resValue = myDictionary[key];
}
法二:TryGetValue方法:
int resValue ;
myDictionary.TryGetValue(key, out resValue);
根据key取value,最好使用 TryGetValue 而不是 ContainsKey+ 根据key索引value。使用TryGetValue更快,性能更好,因为只用了一次查找,TryGetValue 比 ContainsKey 后使用[key]取value,速度快一倍。TryGetValue更安全,找不到value时返回false;而使用ContainsKey后使用[key]取value取不到时,会抛出异常导致真机卡死。
string GetDictionaryVal(string strkey)
{
    if (!dicTest.ContainsKey(strkey))
    {
        return string.Empty;
    }

    return dicTest[strkey];
}
上面这段代码其实非常正确,但是从效率的角度上看却对dictionary进行两遍的查找:ContainsKey和下标操作各一次。所以我们可以这么写:
string GetDictionaryVal(string strkey)
{
    string strVal = string.Empty;
    dicTest.TryGetValue(strkey, out strVal);
    return strVal;
}
TryGetValue函数的返回值为bool值,表示是否存在于Dictionary中。


如果你还看不懂我最后给你举一个通俗的例子:
有一缸米,你想在在每一粒上都刻上标记,不重复,相当于“键”当你找的时候一一对应不会找错,这就是这个泛型的键的-作用,而米可以一样,我的意思你明白了吧?

  • 常用属性

  • 名称说明
    Comparer获取用于确定字典中的键是否相等的 IEqualityComparer<T>。
    Count获取包含在 Dictionary<TKey, TValue> 中的键/值对的数目
    Item获取或设置与指定的键相关联的值。
    Keys 获取包含 Dictionary<TKey, TValue> 中的键的集合。
    Values 获取包含 Dictionary<TKey, TValue> 中的值的集合。
  • 常用方法

名称说明
Add  将指定的键和值添加到字典中。
Clear从 Dictionary<TKey, TValue> 中移除所有的键和值
ContainsKey  确定 Dictionary<TKey, TValue> 是否包含指定的键
ContainsValue  确定 Dictionary<TKey, TValue> 是否包含特定值
GetEnumerator返回循环访问 Dictionary<TKey, TValue> 的枚举器
GetObjectData实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary<TKey, TValue> 实例所需的数据
GetType获取当前实例的 Type。 (继承自 Object。)
MemberwiseClone创建当前 Object 的浅表副本。 (继承自 Object。)
OnDeserialization实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。
Remove从 Dictionary<TKey, TValue> 中移除所指定的键的值 TryGetValue 获取与指定的键相关联的值。
Equals(Object) 确定指定的 Object 是否等于当前的 Object。 (继承自 Object。
Finalize允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。(继承自 Object。)
GetHashCode用作特定类型的哈希函数。 (继承自 Object。)
-------------------------------------------------------------------------

c# 对dictionary类进行排序用什么接口实现

如果使用.Net Framework 3.5的话,事情就很简单了。呵呵。
如果不是的话,还是自己写排序吧。

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace DictionarySorting    //排序,通过KeyValuePair遍历元素
{
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 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()方法相应于从数据库里读取到了公司信息。

///
/// 定义Key为string类型,Value为int类型的一个Dictionary
///
///
protected Dictionary SetKeyValue()
{
Dictionary<int,string>dic=new Dictionary<int,string>();
dic.Add("公司1", 1);
dic.Add("公司2", 2);
dic.Add("公司3", 3);
dic.Add("公司4", 4);
return dic;
}

///
/// 得到根据指定的Key行到Value
///
protected void GetKeyValue()
{
Dictionary myDictionary = SetKeyValue();
//测试得到公司2的值
int directorValue = myDictionary["公司2"];
Response.Write("公司2的value是:" + directorValue.ToString());
}

该文章在 2021/3/5 16:10:33 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved