最近使用了Dictionary,出现了意想不到的错误,先记录一下自己遇到的问题以及目前我的解决方法,然后温习一下Dictionary的基础用法。
1、代码如下
namespace DictionaryExample
{
class Program
{
static void Main(string[] args)
{
string[] pedlarArray = {"小明","小王","小红"};
Dictionary<Apple, string[]> appleMessageDict = new Dictionary<Apple, string[]>();
appleMessageDict.Add(new Apple() {
Quantity = 20,
Price = 5
}, pedlarArray);
Console.WriteLine("appleMessageDict.Values.Count:{0}", appleMessageDict.Count);
Console.WriteLine("appleMessageDict.Keys.Count:{0}", appleMessageDict.Keys.Count);
Console.WriteLine("appleMessageDict.Values.Count:{0}", appleMessageDict.Values.Count);
Console.ReadKey();
}
}
public class Apple
{
private int _quantity;
private float _price;
public int Quantity
{
get { return _quantity; }
set
{
_quantity = value;
}
}
public float Price
{
get { return _price; }
set
{
_price = value;
}
}
public Apple()
{
}
}
}
运行结果:
2、原因分析
代码里面的字典AppleMessageDict的value是字符串数组类型,key是一个类类型。为什么数量都是1呢?通过分析我发现appleMessageDict.Count、appleMessageDict.Keys.Count、appleMessageDict.Values.Count这三个统计count的方式仅仅是针对于字典本身的统计,无关key/value是什么类型,仅仅是统计字典包含多少键值对。如果每个键值对中的key或者value是集合,想要知道key或者value的数量,需要另外处理。
3、目前我的解决方法
static void Main(string[] args)
{
int length = 0;
string[] pedlarArray = { "小明", "小王", "小红" };
Dictionary<Apple, string[]> appleMessageDict = new Dictionary<Apple, string[]>();
appleMessageDict.Add(new Apple()
{
Quantity = 20,
Price = 5
}, pedlarArray);
foreach (KeyValuePair<Apple, string[]> pair in appleMessageDict)//目前只能循环统计字典的数量
{
length += pair.Value.Length;
}
Console.WriteLine("appleMessageDict的数量:{0}", length);
//Console.WriteLine("appleMessageDict.Values.Count:{0}", appleMessageDict.Count);
//Console.WriteLine("appleMessageDict.Keys.Count:{0}", appleMessageDict.Keys.Count);
//Console.WriteLine("appleMessageDict.Values.Count:{0}", appleMessageDict.Values.Count);
Console.ReadKey();
}
二、Dictionary的基础知识
1、Dictionary的概念
Dictionary<[key], [value]>是一个泛型,Dictionary是一种变种的HashTable,是一个表示键和值的集合。
2、Dictionary的特点
键必须是唯一的,而值不需要唯一的 。键和值都可以是任何类型。通过一个键读取一个值的时间是接近O(1) 。
3、Dictionary的构造函数
(1)Dictionary<TKey,TValue>()构造函数:初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有默认的初始容量(Dictionary的默认大小为3)并为键类型使用默认的相等比较器。key不可重复,区分大小写
static void Main(string[] args) { #region Dictionary构造函数 (key不可重复,区分大小写) Console.WriteLine("==========Dictionary普通构造函数! key不可重复,区分大小写==========="); Dictionary<string, string> dict =new Dictionary<string, string>(); dict.Add("a","1"); try { dict.Add("A", "1"); foreach (KeyValuePair<string,string> item in dict) { Console.WriteLine("Key:{0},Value:{1}", item.Key,item.Value); } } catch (ArgumentException) { Console.WriteLine("键A已经存在!"); } Console.WriteLine("输入任意值,执行下一个构造函数:"); Console.ReadKey(); }