内容显示页
 
类别:.Net + C# | 浏览(784) | 2009-11-24 11:31:14

using System;
using System.Collections.Generic;

class DictionaryDemo
{
    static void Main(string[] args)
    {
        DictionaryDemo001();
        Console.ReadLine();

        DictionaryDemo002();
        Console.ReadLine();

        DictionaryDemo003();
        Console.ReadLine();
    }

    /// <summary>
    /// 一般用法
    /// </summary>
    static void DictionaryDemo001()
    {
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(1, "111");
        dict.Add(2, "222");

        //判断是否存在相应的key并显示
        if (dict.ContainsKey(2))
        {
            Console.WriteLine(dict[2]);
        }

        //遍历Keys
        foreach (var item in dict.Keys)
        {
            Console.WriteLine("Key:{0}", item);
        }

        //遍历Values
        foreach (var item in dict.Values)
        {
            Console.WriteLine("value:{0}", item);
        }

        //遍历整个字典
        foreach (var item in dict)
        {
            Console.WriteLine("key:{0} value:{1}", item.Key, item.Value);
        }
    }

    /// <summary>
    /// 参数为其它类型
    /// </summary>
    static void DictionaryDemo002()
    {
        Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
        dict.Add("1", "1,11,111".Split(','));
        dict.Add("2", "2,22,222".Split(','));
        Console.WriteLine(dict["2"][2]);
    }

    /// <summary>
    /// 调用自定义类
    /// </summary>
    static void DictionaryDemo003()
    {
        Dictionary<int, yongfa365> dict = new Dictionary<int, yongfa365>();
        for (int i = 0; i < 10; i++)
        {
            yongfa365 y = new yongfa365();
            y.UserCode = i;
            y.UserName = "www.yongfa365.com " + i.ToString();
            dict.Add(i, y);
        }
        foreach (var item in dict)
        {
            Console.WriteLine("{0} One:{1} UserName:{2}", item.Key, item.Value.UserCode, item.Value.UserName);
        }
    }
}

class yongfa365
{
    public int UserCode { get; set; }
    public string UserName { get; set; }

}

引用本页地址:http://www.yongfa365.com/item/Dictionary.html
 
 
相关链接
 
网友评论:
1 'or'='or' - 2010-1-9 17:33:52
'or'='or'
 
2 wall-Z - 2010-1-15 13:42:00
为何以上代码难以编译成功
 
3 wall-Z - 2010-1-15 13:43:18
var 在C#中是何意思?
 
4 匿名网友 - 2010-1-15 13:43:27
建一个Console项目,然后把这代码都复制并替换原代码
 
5 匿名网友 - 2010-1-15 13:44:01
var呀,你查下,通用类型吧
 
姓名: 记住我
网址:
邮箱:
内容:
验证码:  验证码图片 看不清? 换张图试试
 
     
 
 
文章分类
 
 
专题(3)
 
.Net + C#(54)
 
 
ASP+VBS(159)
 
 
 
Linux(10)
 
 
 
web 2.0(24)
 
 
 
 
 
心程(66)
 
生活(95)
 
 
     

Power by :柳永法(yongfa365)'Blog  | 京ICP备07011491号  QQ:64049027  E-mail:64049027qq.com yongfa365'CodePlex

转载请注明来源,以便后人及时得到最新、修正、加强版!!!