C# Dictionary loses keys and values - c#

i have a problem with updating keys and values in dictionary, dictionary loses data everytime when new StreamReader runs on. I wanted StreamReader to read list and when it reads second path keys and values in dictionary are already lost. I would be greateful for help.
class TT_connect
{
public Dictionary<string, double> s_c = new Dictionary<string, double>();
public TT_connect(List<string> tempAS){
Dictionary<string, double> s_a = new Dictionary<string, double>();
foreach(string a in tempAS)
{
using (var s = new StreamReader(a))
{
while (!s.EndOfStream)
{
var l_a = s.ReadLine();
var l_b = l_a.Split(';');
if (s_a.Keys.Contains(l_b[0]))
{
double.TryParse(l_b[1], out double l1);
s_a[l_b[0]] += l1;
}
if (!s_a.Keys.Contains(l_b[0]))
{
double.TryParse(l_b[1], out double l2);
s_a.Add(l_b[0], l2);
}
}
}
}
foreach(KeyValuePair<string,double> s in s_a)
{
s_c.Add(s.Key, s.Value);
}
}
}

Based on Roberts comments i have tried to clean up the implementation a bit.
class TT_connect
{
private string _fileLocation;
public Dictionary<string, double> dict;
public TT_connect(string fileLocation)
{
dict = new Dictionary<string, double>();
_fileLocation = fileLocation;
}
public void FillDictionary()
{
using (var s = new StreamReader(_fileLocation))
{
int lineCount = 0;
while (!s.EndOfStream)
{
string line = s.ReadLine();
lineCount++;
string key = line.Split(';')[0];
string stringValue = line.Split(';')[1];
if (!Double.TryParse(stringValue, out double val))
throw new Exception($"Can't pass value on line: {lineCount}");
if (dict.Keys.Contains(key))
{
dict[key] += val;
}
else
{
dict.Add(key, val);
}
}
}
}
}

Here's what I recommend:
Instantiate your class's dictionary field in the class constructor. That's all you should do in the constructor. Or, go ahead and let it instantiate automatically, as you do now, and forego the constructor entirely.
Provide an Add method that replaces the code in your previous constructor. Use it to do the work of adding your dictionary/stream items. You won't need another dictionary; just add the items to your class's dictionary, directly.
Your current logic does a bit too much in the constructor, and overall there is more logic in your class than you actually need to get the job done.

Related

Writing into nested Dictionary in Unity3D

Can I not write values into my nested dictionary directly?
It would be nice if I could access it like this:
public Dictionary<string, Dictionary<string, Dictionary<string, int>>> planets =
new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();
planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
But I'm getting:
KeyNotFoundException: The given key was not present in the dictionary.
Does this mean I got to insert my Keys after each other?
Does this mean I got to insert my Keys after each other?
Yes, you need to initialize each in order:
planets[Planet.CharacterId] = new Dictionary<string, Dictionary<string, int>>();
planets[Planet.CharacterId]["MetalMine"] = new Dictionary<string, int>();
planets[Planet.CharacterId]["MetalMine"]["Level"] = 0;
You could use collection initializer syntax here, but that won't make stuff much more readable nor maintainable.
Instead of a dictionary of dicionaries of dictionaries you seem to be better off using a class:
public class Planet
{
public List<Mine> Mines { get; set; }
}
public class Mine
{
public string Type { get; set; }
public int Level { get; set; }
}
var planets = new Dictionary<string, Planet>();
planets[Planet.CharacterId] = new Planet
{
Mines = new List<Mine>
{
new Mine
{
Type = "Metal",
Level = 0
}
};
}
It's may be helpful or Nested dictionary alternative.
Create Sample.cs script and test it.
public Dictionary<string,Tuple<string,string,string,int>> _planets = new Dictionary<string, Tuple<string,string, string, int>>();
void Start()
{
string myKey = string.Concat("1","MetalMine","Level");
if(!_planets.ContainsKey(myKey))
{
_planets.Add(myKey,Tuple.Create("1","MetalMine","Level",0));
}
Debug.Log("_planets mykey "+myKey+" ==> "+_planets[myKey].Item4);
}

C# Calling a dictionary within an extension class?

Re-written everything exactly as my program has it:
class DictionaryInitializer
{
public class DictionarySetup
{
public string theDescription { get; set; }
public string theClass { get; set; }
}
public class DictionaryInit
{
//IS_Revenues data
public Dictionary<int, DictionarySetup> accountRevenue = new Dictionary<int, DictionarySetup>()
{
{ 400000, new DictionarySetup {theDescription="Call", theClass="Revenues"}},
{ 400001, new DictionarySetup {theDescription="Bill", theClass="Revenues"}},
{ 495003, new DictionarySetup {theDescription="Revenue", theClass="Revenues"}}
};
public Dictionary<int, DictionarySetup> accountExpenses = new Dictionary<int, DictionarySetup>()
{
{790130, new DictionarySetup { theDescription="Currency Hedge", theClass="Other income/expense"}},
{805520, new DictionarySetup { theDescription="Int Income", theClass="Other income/expense"}}
};
}
On my mainform:
DictionaryInit theDictionary;
btnClick() {
theDictionary = new DictionaryInit();
//Some code to loop through a datagridview
//Somemore Code
foreach (var item in theDictionary.accountRevenue)
{
int theKey = item.Key;
if (theKey == keyCode)
{
DictionarySetup theValues = item.Value;
DGVMain.Rows[rowindex].Cells[3].Value = theValues.theDescription;
DGVMain.Rows[rowindex].Cells[11].Value = theValues.theClass;
DGVMain.Rows[rowindex].Cells[12].Value = "Sale of Services";
Recording(rowindex);
}
}
}
Current work in progress:
DictionarySetup theValue;
if (theDictionary.accountExpenses.TryGetValue(keyCode,out theValue.theDescription) //[5]-> Account Type
{
//Some code to write dictionary data to the data grid view.
I'm working on making the TryGetValue and Contains(value) dictionary functions to work for now.
My current error messages are as follows:
"a property or indexer may not be passed as an out or ref parameter" when attempting the trygetvalue
and finally when trying the extension method i'm trying to create:
"Inconsistent accessibility, Dictionary<int, DictionaryInitializer.DictionarySetup> is less accessible than the method DictionaryUse<int, DictionaryInitializer.DictionarySetup>"
You have to make your field public....
Dictionary<int, DictionarySetup> accountRevenue
should be
public Dictionary<int, DictionarySetup> accountRevenue
if you want to refer to it from outside the class..
This part seems to also be missing a variable name;
public void DictionaryUse (int code, int key, Dictionary)
should be
public void DictionaryUse (int code, int key, Dictionary<int, DictionarySetup> theDictionary)
But I agree with the other comments, you seem to be re-inventing the wheel, just use the existing Dictionary utility methods

Converting an anonymous object's properties and values to a Dictionary

I am creating a library for an existing API. I currently have QueryParameter classes for each request class. The QueryParameter classes are simple but they do vary (not all requests take the same query parameters).
Here is an example of a QueryParameter class:
public class ApiRequestAQueryParameters
{
public string Name { get; set; }
public int Start { get; set; }
public int Stop { get; set; }
}
I am interested in a way to convert a class like this into a Dictionary that I can feed to our Web client. I am hoping to have a reusable method like:
private Dictionary<string, string> GenerateQueryParameters(object queryParametersObject)
{
// perform conversion
}
This way I won't have to pull out the QueryParameter properties for each request (there will be dozens of requests)
The reason that I am using QueryParameter classes instead of making QueryParameter a Dictionary property of each API request class is to be developer friendly. I want to make it so that others can build these API requests by looking at the classes.
There are 2 ways: 1) use reflection and 2) serialize to json and back.
Here is the 1st method:
private Dictionary<string, string> GenerateQueryParameters(object queryParametersObject)
{
var res = new Dictionary<string, string>();
var props = queryParametersObject.GetType().GetProperties();
foreach (var prop in props)
{
res[prop.Name] = prop.GetValue(queryParametersObject).ToString();
}
return res;
}
You can do something like this:
private Dictionary<string, string> GenerateQueryParameters(object queryParameters)
{
var startStop = new StartStop() { Start = queryParameters.Start, Stop = queryParameters.Stop};
var result = new Dictionary<string, string>();
result.Add(queryParameters.Name, startStop);
return result;
}
public class StartStop
{
public int Start { get; set; }
public int Stop { get; set; }
}
This may be the perfect case to utilize ExpandoObjects. An ExpandoObject is a dynamic type, whose properties can be created at run time. ExpandoObject implements IDictionary < string, object > so it's easy to convert to a Dictionary < string, object > .
In the example below, an ExpandoObject is created and converted to a Dictionary < string, object > and then converted to a Dictionary < string, string >.
dynamic apiVar = new ExpandoObject();
apiVar.Name = "Test";
apiVar.Start = 1;
apiVar.Stop = 2;
var iDict = (IDictionary<string, object>) apiVar;
/* if you can utilize a Dictionary<string, object> */
var objectDict = iDict.ToDictionary(i => i.Key, i => i.Value);
/* if you need a Dictionary<string, string> */
var stringDict = iDict.ToDictionary( i=>i.Key, i=> i.Value.ToString());
There are also different ways of setting properties on an ExpandoObject. Below is an example of setting a property by a variable name.
dynamic apiVar = new ExpandoObject();
var propertyName = "Name";
apiVar[propertyName] = "Test";
propertyName = "Start";
apiVar[propertyName] = 1;
propertyName = "Stop";
apiVar[propertyName] = 2;
I always reuse the RouteValueDictionary class for this. It has a constructor that accepts any object and the class itself implements IDictionary.
It's available in the System.Web dll
private Dictionary<string, string> GenerateQueryParameters(object queryParametersObject)
{
return new RouteValueDictionary(queryParametersObject).ToDictionary(d => d.Key, d => Convert.ToString(d.Value));
}

Cannot update a single item (object) in a List C#

I have a list of objects:
List<NPortfolio> Portfolios = new List<NPortfolio>();
Portfolios.Add(new NPortfolio(1, "1", emptyPositions));
Portfolios.Add(new NPortfolio(2, "2", emptyPositions));
Now i want to call a Method on the object that modifies its properties:
Portfolios[0].UpdatePositions(db.GetPortfolio(1, Today));
The method is this:
public void UpdatePositions(Dictionary<string, double> valuepairs)
{
foreach (var k in this.positions.Keys.ToList())
{
if (valuepairs.ContainsKey(k))
this.positions[k] = valuepairs[k];
}
}
This works, but the problem is that when I try to update just the first item of the list:
Portfolios[0].UpdatePositions(db.GetPortfolio(1, Today));
ALL ITEMS OF THE LIST ARE UPDATED!!!
I cannot find why all items are updated and not only item 0.
Please help this is really an headache
many thanks
class definition:
public class NPortfolio
{
public string p_id { get; set; }
public int p_nr { get; set; }
private Dictionary<string, double> positions;
public NPortfolio(int nr, string id, Dictionary<string, double> pos)
{
p_nr = nr;
p_id = id;
positions = pos;
}
public void UpdatePositions(Dictionary<string, double> valuepairs)
{
foreach (var k in this.positions.Keys.ToList())
{
if (valuepairs.ContainsKey(k))
this.positions[k] = valuepairs[k];
}
}
public Dictionary<string, double> getPositions()
{
return positions;
}
}
The problem is from this
Portfolios.Add(new NPortfolio(1, "1", emptyPositions));
Portfolios.Add(new NPortfolio(2, "2", emptyPositions));
You are passing the same dictionary to both classes, so if you modify one of the classes you modify both instances.
You must create a new dictionary inside the constructor of NPortfolio so each class has a unique copy.
public NPortfolio(int nr, string id, Dictionary<string, double> pos)
{
p_nr = nr;
p_id = id;
positions = new Dictionary<string, double>(pos);
}
This will make a shallow copy of the dictionary and should solve your issue for now.
You're passing the same dictionary into your objects. So when you update it in one you end up seeing the changes in the other. You should create a new dictionary inside your constructor and populate it with the values passed in.
public NPortfolio(int nr, string id, Dictionary<string, double> pos)
{
p_nr = nr;
p_id = id;
positions = new Dictionary<string, double>(pos);
}

Foreach Loop using KVP to iterate through a Multi-Dimensional List

I want to use a foreach k, v pairs loop to run through a multidimensional list, and output those values elsewhere. Here is the code:
public class LogTable
{
public string FunctionName { get; set; }
public string LogTime { get; set; }
}
public class TableVars
{
public List<LogTable> loggingTable { get; set; }
public TableVars()
{
loggingTable = new List<LogTable>();
}
public void createLogList()
{
loggingTable = new List<LogTable>();
}
}
foreach( KeyValuePair<string, string> kvp in tablevars.loggingTable)
{
// output would go here. I haven't looked it up yet but I assume it's something
// along the lines of var = k var2 = v? Please correct me if I'm wrong.
}
When I run my mouse over 'foreach' I get a warning saying - 'Cannot convert type 'DataObjects.LogTable' to 'System.Collections.Generic.KeyValuePair. How can I resolve this issue, or is there a more efficient way to accomplish the same goal?
Thanks!
I should have added more context, sorry. I'm trying to return the two different values inside the properties 'FunctionName' and 'LogTime' which I have added via:
var tablevars = new TableVars();
tablevars.loggingTable.Add(new LogTable { FunctionName = errorvalue, LogTime = logtime });
To specify more accurately, the intention of the foreach k, v loop was to grab every distinct property of FunctionName and LogTime and input them into a database in SQL Server. This is why the distinction between k, v (or FunctionName, LogTime) is important. Again, please correct me if I'm wrong.
You cannot use KeyValuePair<>, because you don't enumerate a Dictionary<>. But you don't need to, simply do this:
foreach(LogTable logTable in tablevars.loggingTable)
{
// do whatever with logTable.FunctionName and logTable.LogTime
}
Either change your foreach to iterate through List<LogTable>
foreach( LogTable lt in tablevars.loggingTable)
{...}
OR
Use a KeyValuePair instead of creating class LogTable
public class TableVars
{
public Dictionary<string,string> loggingTable { get; set; }
public TableVars()
{
loggingTable = new Dictionary<string,string>();
}
public void createLogList()
{
loggingTable = new Dictionary<string, string>();
}
}
foreach( KeyValuePair<string, string> kvp in tablevars.loggingTable)
{
//loggingTagle is now a KeyValuePair
}

Categories

Resources