Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to add data to my dictionary, but at the end I find I only have replicas of a single object; here is my code
C#
while (!rst.EOF)
{        
    Data d = Read(rst) as Data;
    MapToObject.Add(d.Id, d);
    rst.MoveNext();
}


At the end MapToObject contains a replica of the last data added. What can I do to fix it?
-the MapToObject is just a dictionary int,object
-Read(rst) is just a function that takes the elemet from rst and stor it to d
-rst is just a database record

What I have tried:

d = Read(rst) as Data;
MapToObject.Add(d.Id,new object());
MapToObject[d.Id] = d;
Posted
Updated 22-Feb-16 3:55am
v2

The method Dictionary<TKey,TValue>.Add(TKey key, TValue value) will throw an exception if you try to insert a second identical key (whereas setting a value via the indexer property (MapToObject[d.Id] = d;) will simply overwrite an existing entry with the same key).

So if you do not get an exception and you end up with only one entry in your Dictionary then your while-loop only ran once before rst.EOF became true.

If you do have more than one entry then at least the keys have to be different. In that case you probably didn't actually specify d as the value to be inserted but instead new object() like you've shown under "What I have tried".
 
Share this answer
 
Comments
BillWoodruff 23-Feb-16 3:13am    
+5
Sascha Lefèvre 23-Feb-16 6:37am    
Thank you, Bill!
The Dictionary<int, object> class can't store duplicate key values - the Add method throws and exception if you try.
So it isn't containing a duplicate - the integer value for each record in the Dictionary must be different for each one. And since you get this value from the instance of the Data class you are adding, it stands to reason that the ID value is different in each instance you add, at the point at which you add it.
However, that doesn't mean that you aren't adding the same value repeatedly and overwriting it's Id and other properties in your Read method.
I'd start there by checking that it creates a new instance each time it's called rather than "recycling" a single instance, and use the debugger to work out exactly what is happening if it wasn't obvious from that.
 
Share this answer
 
Comments
Member 11736914 22-Feb-16 10:34am    
you were right about the read function i wasn't creating a new instence each time i used it
OriginalGriff 22-Feb-16 11:03am    
:thumbsup:
BillWoodruff 23-Feb-16 3:13am    
+5

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