泛型字典

来源:互联网 发布:淘宝动漫周边网店 编辑:程序博客网 时间:2024/06/08 16:08
static Dictionary<String,int> CountWords(string text){//创建从单词到频率的Dictionary<string,int> frequencies;frequencies = new Dictionary<string,int>();       //将文本分解成单词    string[] words = Regex.Split(text,@"\W+");//添加或更新映射    foreach(string word in words){        if(frequencies.ContainsKey(word)){frequencies[word]++;}else{frequencies[word] = 1;}}   return frequencies;}void Main(){string text = @"Do you like green eggs and ham?                I do not like them,Sam-I-am.                I do not like green eggs and ham.";Dictionary<string,int> frequencies = CountWords(text);foreach(KeyValuePair<string,int> entry in frequencies){string word = entry.Key;int frequency = entry.Value;Console.WriteLine("{0},{1}",word,frequency);}}
keyValuePair翻译过来就是键值对,也就是一个一对一的数据类型,它是值类型,可以理解为Dictionary(字典)的基本单元。
Dictionary.ContainsValue 方法 :确定 Dictionary 是否包含特定值。
IEnumerable<KeyValuePair<TKey,TValue>> "双重泛型"接口 ---它是一个IEnumerable<T>接口,其类型实参是KeyValuePair<string,int>结构。
泛型方法:

列表<T> .ConvertAll <TOutput>方法:将当前List <T>中的元素转换为另一个类型,并返回一个包含转换元素的列表。

static double TakeSquareRoot(int x){return Math.Sqrt(x);}void Main(){//创建并填充一个整数列表List<int> integers = new List<int>();integers.Add(1);integers.Add(2);integers.Add(3);integers.Add(4);//创建委托实例Converter<int,double> converter = TakeSquareRoot;List<double> doubles;//调用泛型方法来转换列表doubles = integers.ConvertAll<double>(converter);foreach(double d in doubles){Console.WriteLine(d);}}


原创粉丝点击