Reputation: 923
Dictionary<string, string> f = new Dictionary<string, string>();
Dictionary<int, Dictionary<string, string>> lines = new Dictionary<int, Dictionary<string, string>>();
while ((line = sr.ReadLine()) != null)
{
lineArr = line.Split(',');
int x = 0;
foreach (string field in lineArr)
{
f.Add(keys[x], field);
x++;
}
lines.Add(lineIndex, f);
f.Clear();
lineIndex++;
Dictionary f is temporary and I want to store its value inside another Dictionary, but once I Clear() it the value in Dictionary lines gets lost, I guess it delivers some kind of reference. Any idea how to solve this?
Upvotes: 0
Views: 792
Reputation: 128317
The variable f
holds a reference to a Dictionary<string, string>
object. When you add it to another dictionary, you're not creating a new object, only another reference to the same object.
I'd highly recommend just going with f = new Dictionary<string, string>()
as the path of least resistence here.
Upvotes: 2
Reputation: 50835
Move the declaration of f
inside your loop. Then you won't have to empty it each time and the reference remains intact:
Dictionary<int, Dictionary<string, string>> lines = new Dictionary<int, Dictionary<string, string>>();
while ((line = sr.ReadLine()) != null)
{
Dictionary<string, string> f = new Dictionary<string, string>();
lineArr = line.Split(',');
int x = 0;
foreach (string field in lineArr)
{
f.Add(keys[x], field);
x++;
}
lines.Add(lineIndex, f);
lineIndex++;
Upvotes: 8