Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
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());
}


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,
Posted

Assumption: i is the key and, newFrame is the new value.


You can do it like the follwing:


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

FrameID.Add(i, newFrame);
 
Share this answer
 
v2
C#
frames f = null;
if(FrameID.TryGetValue(frameno, out f))
{
   // frameno is in dictionary
   FrameID[frameno] = val;
}
else 
   FrameID.Add(frameno, val);
 
Share this answer
 
Just treat it as an array.
This uses strings, but that's just because it is easier to see what is going on.

C#
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);
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900