C# Dictionary

Dictionary有Key跟Value,一个Key只能对应一种Value,但一种Value可以对应很多种Key
像是学生座号和成绩,每个人只会对应到一个成绩,但也许有人同时考到相同的分数

下面是官方的范例

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys.
        //
        Dictionary<string, string> openWith = new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the dictionary.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }
      #output => An element with Key = "txt" already exists.

 */

看不懂的话 可以参考这篇
http://code2study.blogspot.com/2012/01/c-dictionary.html

      
Dictionary<string, string> MyDic = new Dictionary<string, string>( );

// 建立字典
private void CreateDictionary( )
{
    MyDic.Add( "Name", "Jack" );
    MyDic.Add( "Blog", "Jack’s Blog" );
    MyDic.Add( "Group", "KTV Group" );
}

// 查字典
private String FindInDictionary( String FindMe )
{
    if ( true == ( MyDic.ContainsKey( FindMe ) ) )
    {
        return MyDic[ FindMe ];
    }
    else
    {
        return "Not Found";
    }
}

// 巡整個字典
private void ShowAllInDictionary( )
{
    foreach ( var OneItem in MyDic )
    {
        Console.WriteLine( "Key = " + OneItem.Key + ", Value = " + OneItem.Value );
    }
}

除了上面那種先宣告再Add的方式之外,也可以用底下的方式來直接宣告並產生內容

Dictionary<string, string> dctNewWay =
        new Dictionary<string, string>()
        {
            {"Key1", "AAAA"}, {"Key2", "BBBB"},
            {"Key3", "CCCC"}, {"Key4", "DDDD"}
        };

另外,值得一提的是,Key跟Value並不限定只能用String,什麼型別都可以,所以你也可以把Class塞到Value,然後其中一個屬性拿出來當作Key,就可以方便的確認有沒有重複的Key,不用塞到SQL才知道。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值