如何基于Key IN C#更新字典中的值 [英] How to Update a value in Dictionary based on Key IN C#

查看:259
本文介绍了如何基于Key IN C#更新字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
谁能给我一个示例,说明如何根据密钥更新字典中的值.

我在词典中有很多帧

Hi all,
can any one give me a sample how to update a value in dictionary based upon the key.

I have a collection of frames in a Dictionary

public Dictionary<int,frames> FrameID=new Dictionary<int,> ();
System .IO .DirectoryInfo myimagesdir=new System .IO.DirectoryInfo(@".\\tmp");
			
foreach(System .IO.FileInfo myimagesfile in myimagesdir.GetFiles("*.jpg"))
{
frameno=frameno+1;
FrameID.Add(frameno,new Frames());
}



现在,我想基于密钥更新帧.就像对于key = 1一样,我想添加其他框架(已被编辑).
如何使用新编辑的框架更新旧框架.

谢谢,



Now i want to update frames based on the key. like for key=1 i want to add different frame(which is edited one).
how can i update old frame with new edited frame .

Thanks,

推荐答案

假设:i是键,newFrame是新值.

您可以像下面这样:

if (FrameID.ContainsKey(i))
{
    FrameID.Remove(i);
}

FrameID.Add(i, newFrame);


frames f = null;
if(FrameID.TryGetValue(frameno, out f))
{
   // frameno is in dictionary
   FrameID[frameno] = val;
}
else 
   FrameID.Add(frameno, val);


只需将其视为数组即可.
它使用字符串,但这仅仅是因为它更容易看到正在发生的事情.

Just treat it as an array.
This uses strings, but that''s just because it is easier to see what is going on.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(0, "zero");
dict.Add(1, "one");
dict.Add(2, "two");
foreach (KeyValuePair<int, string> kvp in dict)
    {
    Console.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
    }
dict[1] = "une";
foreach (KeyValuePair<int, string> kvp in dict)
    {
    Console.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
    }


这篇关于如何基于Key IN C#更新字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆