从字典

时间:2015-12-16 03:13:28

标签: c# dictionary

我有一个var myDictionary = new Dictionary<int, string>,其中包含以下数据:

123, "Do this"
234, "Do that"
345, "Do something"
123, "Do that"
567, "Do anything"
234, "Do something"

对于我来说,只检索任何给定键的值的最佳方法是什么?说,我只想获得123的值。

3 个答案:

答案 0 :(得分:4)

如果您希望将多个不同的值分组在一个键下,则可能需要将字典的结构更改为以下内容:

var myDictionary = new Dictionary<int, List<string>>();

然后,您为每个新密钥初始化列表,或者如果密钥已经存在,则将该项添加到列表中。

if (!myDictionary.ContainsKey(myKey))
{
    myDictionary[myKey] = new List<string();
}
myDictionary[myKey].Add(myItem);

你以标准方式获得物品:

if (myDictionary.ContainsKey(myKey))
{
    var results = myDictionary[myKey];
}

这将为您提供一个列表,然后您可以查询该列表以查看已返回的项目。

答案 1 :(得分:1)

Dictionary对象不能包含具有相同键的多个项目。相反,您想使用KeyValuePair

代码可能如下所示:

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

 namespace flexland
 {
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }

         Bitmap newpic; //Put newpic here!

         public void Form1_Load(object sender, EventArgs e)
         {
             Bitmap bmp = new Bitmap(Properties.Resources.pic1in);
             newpic = new Bitmap(bmp); //don't declare newpic here!
             .... //all other initializations
         }

         private void button1_Click(object sender, EventArgs e)
         {
             pictureBox1.Image = newpic; //It should fix the problem
         }       
     }
 }

输出为:

var items = new List<KeyValuePair<int, String>>();

items.Add(new KeyValuePair<int, String>(123, "Do this"));
items.Add(new KeyValuePair<int, String>(234, "Do that"));
items.Add(new KeyValuePair<int, String>(345, "Do something"));
items.Add(new KeyValuePair<int, String>(123, "Do that"));
items.Add(new KeyValuePair<int, String>(567, "Do anything"));
items.Add(new KeyValuePair<int, String>(234, "Do something"));

// This is the key you are looking for
int desiredValue = 123;

foreach (var v in items.Where(kvp => kvp.Key == desiredValue))
{
    // Access the values you need here
    Console.WriteLine(v.Value);
}

您可以在行动here中看到此示例。快乐的编码:)

答案 2 :(得分:1)

见下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication61
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>() {
               {123, new List<string>() {"Do this", "Do that"}},
               {234, new List<string>() {"Do that", "Do something"}},
               {345, new List<string>() {"Do something"}},
               {567, new List<string>() {"Do anything"}}
            };

            List<string> results = dict[123];

        }

    }
}