Automapping Dictionary - c#

I am trying to automap a dictionary to another without replacing existing values with null but just update them with the new ones if necessary. However i can't get it to work anyway.
Code :
class Klass
{
public Dictionary<string, string[]> Dictionary = new Dictionary<string, string[]>();
}
class Main
{
private Klass ex1 = new Klass();
public Main()
{
Mapper.CreateMap<Klass, Klass>().ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
TestRun("1");
TestRun("2");
TestRun("3");
//EVERY CALL REPLACES THE OTHER HERE IDK WHY [OTHER MAPPER VALUES I MEAN]
}
public void TestRun(string text)
{
var ex2 = new Klass();
ex2.Dictionary = new Dictionary<string, string[]>
{
{text, new []{"1", "2... etc as provided"}}
};
Mapper.Map(ex2, ex1);
}
}

Related

C# Dictionary loses keys and values

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.

C# count and list pairs of dict of another method

I have the below code, and I need to find how many, and all pairs, of dictionary, which however belongs in another namespace's method:
using sys = System;
using gen = System.Collections.Generic;
namespace xtra
{
class TestClass
{
public void Sing()
{
gen::Dictionary<string, int> dict = new gen::Dictionary<string, int>()
{
["A"] = 1,
["B"] = 2,
["C"] = 3
};
}
}
}
namespace ConsoleApp99
{
class Program
{
static void Main(string[] args)
{
xtra.TestClass Joe = new xtra.TestClass();
Joe.Sing();
foreach (string name in Joe.Keys) //error!
sys.Console.WriteLine($"{name} {dict[name]}"); //error!
}
}
}
So, the method Sing creates and populates a dictionary, but, upon instantiation in another namespace (in Main), I can create it, but, how do I count pairs and print their values?? I do understand that Joe is a method that makes the dictionary, but I have no clue to reference Joe's dictionary..
The dict property access modifier must be public in order to access him from another class.
Another approach is to expose only the dict property by encapsulating him and make Sing() method private.
class TestClass
{
private Dictionary<string, int> _dict;
public Dictionary<string, int> dict
{
get
{
if (_dict == null)
{
Sing();
}
return _dict;
}
set { _dict = value; }
}
private void Sing()
{
_dict = new Dictionary<string, int>()
{
["A"] = 1,
["B"] = 2,
["C"] = 3
};
}
}
class Program
{
static void Main(string[] args)
{
xtra.TestClass Joe = new xtra.TestClass();
foreach (string name in Joe.dict.Keys)
sys.Console.WriteLine($"{name} {Joe.dict[name]}");
Console.ReadLine();
}
}
You need to define this dictionary as public property inside of TestClass in order to have access to it from different class/namespace:
namespace xtra
{
class TestClass
{
public Dictionary<string, int> Dict { get; set; }
public void Sing()
{
Dict = new Dictionary<string, int>()
{
["A"] = 1,
["B"] = 2,
["C"] = 3
};
}
}
}
namespace ConsoleApp99
{
class Program
{
static void Main(string[] args)
{
xtra.TestClass Joe = new xtra.TestClass();
Joe.Sing();
foreach (string name in Joe.Dict.Keys) //error!
sys.Console.WriteLine($"{name} {Joe.Dict[name]}"); //error!
}
}
}

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

Creating a custom list class in C#

I want to create a class that is a Custom List. So I have done
public class Set1 : List<Dictionary<string, string>>
{
public Set1() : base(List<Dictionary<string, string>>)
{
List<Dictionary<string, string>> mySet = new List<Dictionary<string, string>>()
{
new Dictionary<string, string>()
{
{"first_name","John"},
},
new Dictionary<string, string>()
{
{"last_name","Smith"},
},
};
base(mySet);
}
}
But this does not compile. What am I doing wrong please? Thanks in advance.
You can't call a base/alternate constructor from within the method in C# like you can in some other languages.
However, you don't need to call the base constructor in this case - you can just do:
public Set1()
{
this.Add(
new Dictionary<string, string>()
{
{"first_name","John"},
}
);
this.Add(
new Dictionary<string, string>()
{
{"last_name","Smith"},
}
);
}
If you really want to call the base constructor, though, you'll have to inline the list creation in the declaration:
public Set1()
: base( new List<Dictionary<string, string>>
{
new Dictionary<string, string>()
{
{"first_name","John"},
},
new Dictionary<string, string>()
{
{"last_name","Smith"},
}
}
)
{
// nothing more to do here
}
but that creates a list, only to have the constructor copy the items into the list, increasing your memory usage for a short time.
Here is the code you're looking for
new Dictionary<string, string>() {
{"first_name","John"}, {"last_name","Smith"},
}.
You don't have any need to inherit from List here. What you wanted was an instance of some collection. A class is a general template for data and behaviour, not something you define to hold the specific information for John.
Even better, create a class for the apprioriate thing (a person), and create an instance of a List<Person>
public class Person
{
public string Forename {get;set;}
public string Surname {get;set;}
}
///
var people = new List<Person>() { new Person("John", "Smith") };

.NET Dictionary as a Property

Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.
The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.
Here's a quick example
class Example {
private Dictionary<int,string> _map;
public Dictionary<int,string> Map { get { return _map; } }
public Example() { _map = new Dictionary<int,string>(); }
}
Some use cases
var e = new Example();
e.Map[42] = "The Answer";
sample code:
public class MyClass
{
public MyClass()
{
TheDictionary = new Dictionary<int, string>();
}
// private setter so no-one can change the dictionary itself
// so create it in the constructor
public IDictionary<int, string> TheDictionary { get; private set; }
}
sample usage:
MyClass mc = new MyClass();
mc.TheDictionary.Add(1, "one");
mc.TheDictionary.Add(2, "two");
mc.TheDictionary.Add(3, "three");
Console.WriteLine(mc.TheDictionary[2]);
EDIT
When you use C# version 6 or later, you can also use this:
public class MyClass
{
// you don't need a constructor for this feature
// no (public) setter so no-one can change the dictionary itself
// it is set when creating a new instance of MyClass
public IDictionary<int, string> TheDictionary { get; } = new Dictionary<int, string>();
}
You could also look into indexers. (official MSDN documentation here)
class MyClass
{
private Dictionary<string, string> data = new Dictionary<string, string>();
public MyClass()
{
data.Add("Turing, Alan", "Alan Mathison Turing, OBE, FRS (pronounced /ˈtjʊ(ə)rɪŋ/) (23 June, 1912 – 7 June, 1954) was a British mathematician, logician, cryptanalyst and computer scientist.")
//Courtesy of [Wikipedia][3]. Used without permission
}
public string this [string index]
{
get
{
return data[index];
}
}
}
Then, once you have populated the dictionary internally, you can access it's information by going
MyClass myExample = new MyClass();
string turingBio = myExample["Turing, Alan"];
EDIT
Obviously, this has to be used carefully, because MyClass is NOT a dictionary, and you cannot use any dictionary methods on it unless you implement them for the wrapper class. But indexers are a great tool in certain situations.
In order to ensure the encapsulation is correct and the dictionary cannot be updated outside the class using Add or the form ExampleDictionary[1]= "test", use IReadOnlyDictionary.
public class Example
{
private Dictionary<int, string> exampleDictionary;
public Example()
{
exampleDictionary = new Dictionary<int, string>();
}
public IReadOnlyDictionary<int, string> ExampleDictionary
{
get { return (IReadOnlyDictionary<int, string>)exampleDictionary; }
}
}
The following code will not work, which is not the case if IDictionary is used:
var example = new Example();
example.ExampleDictionary[1] = test;
Another example of using a dictionary as a static property with only the get accessor:
private static Dictionary <string, string> dict = new Dictionary <string,string>(){
{"Design Matrix", "Design Case"},
{"N/A", "Other"}
};
public static Dictionary <string, string> Dict
{
get { return dict}
}
This structure can be used to replace values.
An example...
public class Example
{
public Dictionary<Int32, String> DictionaryProperty
{
get; set;
}
public Example()
{
DictionaryProperty = new Dictionary<int, string>();
}
}
public class MainForm
{
public MainForm()
{
Example e = new Example();
e.DictionaryProperty.Add(1, "Hello");
e.DictionaryProperty.Remove(1);
}
}
Since .net 4.6 you can also define a Dictionary like this:
private Dictionary<string,int> Values => new Dictionary<string, int>()
{
{ "Value_1", 1},
{ "Value_2", 2},
{ "Value_3", 3},
};
It's called Expression-bodied members!
You mean like a property bag ?
http://www.codeproject.com/KB/recipes/propertybag.aspx

Categories

Resources