Dictionary<int, Dictionary<string, string>> dict1 = new Dictionary<int, Dictionary<string, string>>();

Dictionary<int, Dictionary<string, string>> dict2 = new Dictionary<int, Dictionary<string, string>>();

Dictionary<string, string> _dict3 = new Dictionary<string, string>() { { "kkds", "wewer" }, { "ddd", "eeeeer" } };

Dictionary<string, string> _dict4 = new Dictionary<string, string>() { { "ccc", "rrrr" }, { "yyy", "uuuu" } };

Dictionary求符合某些特征的key或者value的值的和,用linq处理方法参考:

    1. private string ReturnDMY_Money(Dictionary<int, string> dic, string i)
    2. {
    3. var r = dic.Sum(x => x.Value.Split('|')[1] == i ? int.Parse(x.Value.Split('|')[0]) : 0);
    4. return r.ToString();
    5. }

C#2.0泛型详细介绍

泛型是 C#2.0 语言和公共语言运行库 (CLR) 中的一个新功能。泛型将类型参数的概念引入 .NET Framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。例如, 通过使用泛型类型参数 T,可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作.
使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。
泛型最常见的用途是创建集合类。
  
.NET Framework 类库在 System.Collections.Generic
命名空间中包含几个新的泛型集合类。应尽可能地使用这些类来代替普通的类,如 System.Collections 命名空间中的
ArrayList,HashTable等。

非泛型类(System.Collections) 对应的泛型类(System.Collections.Generic)
ArrayList List
Hashtable Dictionary
Queue Queue
Stack Stack
SortedList SortedList

使用泛型的建议:

1.如果需要对多种类型进行相同的操作处理,则应该使用泛型。

2。如果需要处理值类型,则使用泛型可以避免装箱拆箱带来的性能开销。

3.使用泛型可以在应用程序编译时发现类型错误,增强程序的健壮性。

4.减少不必要的重复编码,使代码结构更加清晰。

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用List<T>替换ArrayList
            List<string> ls = new List<string>();
            ls.Add("泛型集合元素1");
            ls.Add("泛型集合元素2");
            ls.Add("泛型集合元素3");
            foreach (string s in ls)
                Console.WriteLine(s);

//使用Dictionary<Tkey,Tvalue>
            Console.WriteLine("Dictinary泛型集合类举例");
            Dictionary<string, string> dct = new Dictionary<string, string>();
            dct.Add("键1", "值1");
            dct.Add("键2", "值2");
            dct.Add("键3", "值3");
            foreach (KeyValuePair<string, string> kvp in dct)
                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
           
            //使用Queue<T>
            Console.WriteLine("Queue泛型集合类型:");
            Queue<string> que = new Queue<string>();
            que.Enqueue("这是队列元素值1");
            que.Enqueue("这是队列元素值2");
            foreach (string s in que)
                Console.WriteLine(s);

//使用Stack<T>
            Console.WriteLine("Stack泛型集合类举例");
            Stack<string> stack = new Stack<string>();
            stack.Push("这是堆栈元素1");
            stack.Push("这是堆栈元素2");
            foreach (string s in stack)
                Console.WriteLine(s);

//使用SortedList<Tkey,Tvalue>
            Console.WriteLine("SortedList泛型集合举例");
            SortedList<string, string> sl = new SortedList<string, string>();
            sl.Add("key1", "value1");
            sl.Add("key2", "value2");
            sl.Add("key3", "value3");
            sl.Add("key4", "value4");
            foreach (KeyValuePair<string, string> kvp in sl)
                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);

Console.ReadLine();
        }
       
    }
}

下面我们就来说下,几个泛型集合类的用法:

一.Dictionary
此类在 .NET Framework 2.0 版中是新增的。表示键和值的集合。命名空间:System.Collections.Generic,程序集:mscorlib(在 mscorlib.dll 中)
    class TestGenericList
    {
         static void Main()
        {
//声明对象,参数表示,键是int类型,值是string类型
            Dictionary<int, string> fruit = new Dictionary<int, string>();
            try{
            //加入重复键会引发异常
                fruit.Add(1, "苹果");
                fruit.Add(2, "桔子");
                fruit.Add(3, "香蕉");
                fruit.Add(4, "菠萝");            
   //参数错误将引发异常,如下所示
   //fruit.Add("5", "aa");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("添加错误!!!");
            }
//因为引入了泛型,所以键取出后不需要进行Object到int的转换,值的集合也一样
            foreach (int i in fruit.Keys)
            {
                Console.WriteLine("键是:{0} 值是:{1}",i,fruit);
            }
      //删除指定键,值
            fruit.Remove(1);
             //判断是否包含指定键
            if (fruit.ContainsKey(1))
            {
                Console.WriteLine("包含此键");
            }
            //清除集合中所有对象
            fruit.Clear();
        }
    }
Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同,其它方法如:ContainsKey ,ContainsValue ,Remove 等,使用方法基本一致。

二、List类
注意:此类在 .NET Framework 2.0
版中是新增的。表示可通过索引访问的对象的强类型列表。提供用于对列表进行搜索、排序和操作的方法。命名空
间:System.Collections.Generic,程序集:mscorlib(在 mscorlib.dll 中),List 类是
ArrayList 类的泛型等效类。

//声明一个泛型类  
    class TestGenericList
    {
        static void Main()
        {
            //声明一个List对象,只加入string参数
            List<string> names = new List<string>();
            names.Add("乔峰");
            names.Add("欧阳峰");
            names.Add("马蜂");
            //遍历List
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
            //向List中插入元素
            names.Insert(2, "张三峰");
            //移除指定元素
            names.Remove("马蜂");           
        }
    }

决定使用 List 还是使用 ArrayList 类(两者具有类似的功能)时,记住 List
类在大多数情况下执行得更好并且是类型安全的。如果对 List 类的类型 T 使用引用类型,则两个类的行为是完全相同的。但是,如果对类型 T
使用值类型,则需要考虑实现和装箱问题。

如果对类型 T 使用值类型,则编译器将特别针对该值类型生成 List 类的实现。这意味着不必对 List 对象的列表元素进行装箱就可以使用该元素,并且在创建大约 500 个列表元素之后,不对列表元素装箱所节省的内存将大于生成该类实现所使用的内存。

其实我们也可以自己定义一个泛型类,如下所示:
   //声明一个泛型类
    public class ItemList<T>
    {
        void Add(T item) { }
    }
    class TestGenericList
    {
        private class ExampleClass { }
        static void Main()
        {
            // 声明一个对象,只能加入int型
            ItemList<int> list1 = new ItemList<int>();

//声明一个对象,只能加入Student类型,Student类为自定义类
            ItemList<Student> list2 = new ItemList<Student>();

}
    }

泛型的用法还有很多种,如泛型方法,泛型委托,泛型接口等。

泛型,就是说这个容器内只能装 <>里面的类型。
List <String>中List中装的是String
List <List <String>>中装的是List

以前的List,好比是个箱子,你可以把相近的东西扔在里面
泛型好比是个收纳箱,不但可以放对象,还要在上面标明箱子里面放什么东西

泛形的使用,因为list中的元素添加的是String类型的,使用泛形代表你list中所有元素都为String类型

说白了..就是LIST里再嵌套LIST...
<>使用了泛型,就是告诉JVM该LIST里面装的是什么类型的东西.
List <String>中List中装的是String
List <List <String>>中装的是List,里面的LIST装的是String.

恩恩,就是泛型没错啊,声明数组的时候, <>里面写的就是规定好了的数据类型或类,如:List
<String>就表示这个里面只能装String类型的东东,装不进其他的,至于List <List
<String>>嘛,就是,先来一个装String类型的List,就是里面那个,再来一个装List的List,就是外面那
个,Over!

用泛型的好处是显而易见的性能问题
先看看不用泛型的时候:
List list=new ArrayList();
//list.add();
//填充list
for(int i=0;i <list.size();i++){
  User user=(User)list.get(i);
}
每次取出来的时候都要把Object强转成User类型,据Sun的技术人员说,这样会损失不少性能

用了泛型之后:
List <User> list=new ArrayList <User>();
//list.add();
//填充list
for(int i=0;i <list.size();i++){
  User user = list.get(i);
}
代码变得健壮了不说,而且性能的提高也是非常可观的。

List和string之间的互相转换

我们在开发中经常会用List<string>来保存一组字符串,比如下面这段代码:

List<string> studentNames = new List<string>();

studentNames.Add("John");
studentNames.Add("Mary");
studentNames.Add("Rose");

可是有时候,我们要从中获取一个字符串,字符串的内容就是集合中的内容,但是要用逗号隔开,下面的办法可以实现:

string.Join(", ", studentNames.ToArray())

上面这条语句,返回的结果应该是下面这个样子:

John, Mary, Rose

下面让我们来做个反向工程,从string转换成List<string>

string result = string.Join(", ", studentNames.ToArray());

List<string> newStudentNames = new List<string>(result.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries));

foreach (string s in newStudentNames)
{
    System.Diagnostics.Debug.WriteLine(s);
}

List<string> 与string[] 的区别
2008-01-22 09:58

List<string>   定义强类型化string泛型    List<string> a = new List<string>();会有集合的许多操作,

List<>是一个泛型对象,实例化后相当于是一个List对象。List对象内部可以聚合若干个(理论上不限制大小)同类型对象,并提供很多方便的方法来提供一些基本操作。可以理解为一个封装好的链表对象。

泛型本身的优点
1.类型安全
2.不用频繁的的拆箱装箱

string[]   就是简单的强类型化数组.,没什么好说的。
总的来说,List<>更灵活和方便使用,但是开销更大。

Dictionary<string, string>是一个泛型使用说明

Posted on 2010-08-05 15:03 moss_tan_jun 阅读(5653) 评论(0) 编辑 收藏

Dictionary<string, string>是一个泛型

他本身有集合的功能有时候可以把它看成数组

他的结构是这样的:Dictionary<[key], [value]>

他的特点是存入对象是需要与[key]值一一对应的存入该泛型

通过某一个一定的[key]去找到对应的值

举个例子:

//实例化对象

Dictionary<int, string> dic = new Dictionary<int, string>();

//对象打点添加

dic.Add(1, "one");

dic.Add(2, "two");

dic.Add(3, "one");

//提取元素的方法

string a = dic[1];

string b = dic[2];

string c = dic[3];

//1、2、3是键,分别对应“one”“two”“one”

//上面代码中分别把值赋给了a,b,c

//注意,键相当于找到对应值的唯一标识,所以不能重复

//但是值可以重复

如果你还看不懂我最后给你举一个通俗的例子

有一缸米,你想在在每一粒上都刻上标记,不重复,相当于“键”当你找的时候一一对应不会找错,这就是这个泛型的键的-作用,而米可以一样,我的意思你明白了吧?

-------------------------------------------------------------------------

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());
}

问题:C# Dictionary嵌套使用;结果:嵌套Dictionary添加 , C#2.0泛型详细介绍的更多相关文章

  1. 机器学习入门-贝叶斯构造LDA主题模型,构造word2vec 1.gensim.corpora.Dictionary(构造映射字典) 2.dictionary.doc2vec(做映射) 3.gensim.model.ldamodel.LdaModel(构建主题模型)4lda.print_topics(打印主题).

    1.dictionary = gensim.corpora.Dictionary(clean_content)  对输入的列表做一个数字映射字典, 2. corpus = [dictionary,do ...

  2. mybatis的嵌套查询(嵌套查询nested select和嵌套结果nested results查询)区别

    (转自:http://blog.csdn.net/canot/article/details/51485955) Mybatis表现关联关系比hibernate简单,没有分那么细致one-to-man ...

  3. AJPFX实例集合嵌套之ArrayList嵌套ArrayList

    案例:import java.util.ArrayList;import java.util.Iterator;import com.heima.bean.Person;public class De ...

  4. Dictionary<string, Dictionary<string, Person>> dic = new Dictionary<string, Dictionary<string, Person>>();

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

  5. 代码实现集合嵌套之ArrayList嵌套ArrayList

    package com.loaderman.list; import java.util.ArrayList; import com.loaderman.bean.Person; public cla ...

  6. Android ScrollView嵌套ViewPager,嵌套的ViewPager无法显示

    记录:ScrollView嵌套ViewPager,嵌套的ViewPager无法显示 项目中所需要布局:LinearLayout中包含(orientation="vertical") ...

  7. C# Dictionary.Add(key,value) 与 Dictionary[key]=value的区别

    1. MSDN上的描述. http://msdn.microsoft.com/zh-cn/library/9tee9ht2(v=VS.85).aspx 通过设置 Dictionary 中不存在的键值, ...

  8. extJS4.2.0 Json数据解析,嵌套及非嵌套(二)

    Ext.data.reader.Reader Readers通常用于翻译数据,使其被加载为 Model 实例或Store, 该数据一般是一个AJAX请求的响应数据. 一般情况下不需要直接创建一个Rea ...

  9. angularJs模块ui-router之状态嵌套和视图嵌套

    原文地址:http://bubkoo.com/2014/01/01/angular/ui-router/guide/nested-states%20&%20nested-views/ 状态嵌套 ...

随机推荐

  1. JAXB解析XML为对象

    JAXB支持注解将XML转化为对象,具体看一个简单的例子: <?xml version="1.0" encoding="utf-8"?> <A ...

  2. vim vimdiff diff 使用及命令

    vim: vim 从 vim7 开始加入了多标签切换的功能, 相当于多窗口. 之前的版本虽然也有多文件编辑功能, 但是总之不如这个方便啦.用法::tabnew [++opt选项] [+cmd] 文件  ...

  3. linux下查找最耗iowait的进程

    抓哪个进程干坏事前要先停掉syslogservice syslog stop 打开block dump:echo 1 > /proc/sys/vm/block_dump 统计:dmesg | e ...

  4. Git——基本思想和工作原理(二)

    核心知识点: 1.Git关注文件数据的整体是否发生变化,对更新的文件做一个快照,然后保存一个指向快照的索引,而不会关注文件数据的具体变化. 2.Git版本的更新几乎都发生在本地,不会因为没有网络而不能 ...

  5. Python OOP(2)-static method,class method and instance method

    静态方法(Static Method): 一种简单函数,符合以下要求: 1.嵌套在类中. 2.没有self参数. 特点: 1.类调用.实例调用,静态方法都不会接受自动的self参数. 2.会记录所有实 ...

  6. Thread.currentThread().getContextClassLoader() and Class.getClassLoader()

    Thread.currentThread().getContextClassLoader() and Class.getClassLoader()   一.同一工程中: String path = T ...

  7. STM32 HAL SPI读取MPU6500的设备ID异常

    1.问题背景 近前,使用STM32F4 HAL库的SPI读取MPU6500出现异常. 现象:读取ID失败,返回0,以为硬件焊接问题,各种排查,最后为了示波器测试方便,把读取ID的函数放到While(1 ...

  8. Spark Structured Streaming框架(1)之基本用法

     Spark Struntured Streaming是Spark 2.1.0版本后新增加的流计算引擎,本博将通过几篇博文详细介绍这个框架.这篇是介绍Spark Structured Streamin ...

  9. [算法]Rotate Array

    You may have been using Java for a while. Do you think a simple Java array question can be a challen ...

  10. Python 模块EasyGui

    1.msgBox msgbox(msg='(Your message goes here)', title=' ', ok_button='OK', image=None, root=None) ms ...