How to store a collection of Dictionaries? - c#

I need to create a various number of Dictionary<string, string>s in C#; how can I do so?
I've tried using List<Dictionary<string, string>>, but that doesn't work.

See this example:
List<Dictionary<string,string>> list = new List<Dictionary<string,string>>();
Dictionary<string,string> dict1 = new Dictionary<string,string>();
list.Add(dict1);
list.Add(new Dictionary<string,string>());

List<Dictionary<string,string>> does work. Just do it like this:
var d = new List<Dictionary<string,string>>();
var toAdd = new Dictionary<string,string>();
toAdd["Test"] = "Yes";
d.Add(toAdd);

List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
list.Add(new Dictionary<string, string>());
// list[0].Add(...);

Try
List<Dictionary<string, string>> listDic = new List<Dictionary<string, string>>();
Dictionary<string, string> dic = new Dictionary<string, string>();
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic.Add("key1", "value1");
dic1.Add("key2", "value2");
listDic.Add(dic);
listDic.Add(dic1);

Try,
List<Dictionary<int, string>> a = new List<Dictionary<int, string>>();
Dictionary<int,string> b = new Dictionary<int,string>();
b.Add(1, "Anwer");
a.Add(b);
for (int i = 0; i < a.Count; i++)
foreach (KeyValuePair<int, string> v in a[i])
Console.WriteLine(v.Key + " ------ " + v.Value);

Related

Extract record from dictionary list where key and value does not contains given value list c#

List<Dictionary<string, string>> firstList = new List<Dictionary<string, string>>();
Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("name", "abc");
dict.Add("age", "22");
dict.Add("address", "xyz,aa");
dict.Add("contact", "111");
firstList .Add(dict);
Dictionary<string, string> dict2 = new Dictionary<string,string>();
dict2 .Add("name", "pqr");
dict2 .Add("age", "25");
dict2 .Add("address", "xxx,bb");
dict2 .Add("contact", "4222");
firstList .Add(dict2);
Dictionary<string, string> dict3 = new Dictionary<string,string>();
dict3 .Add("name", "aa");
dict3 .Add("age", "24");
dict3 .Add("address", "xxx,aa");
dict3 .Add("contact", "aaa");
firstList .Add(dict3);
return record where list doesn't not contains key = 'address' and name= 'aa'
Update :- return record where name= 'aa'
Pretty simple with linq:
var result = firstList.Where(x => !(x.ContainsKey("address")
&& x.ContainsKey(name)
&& x["name"] == "aa")).ToList();
and if only one record is required back then use FirstOrDefault():
var result = firstList.Where(x => !(x.ContainsKey("address")
&& x.ContainsKey(name)
&& x["name"] == "aa")).FirstOrDefault();
Don't forget to add on top:
using System.Linq;
UDPATE:
var result = firstList.Where(x =>
&& x.ContainsKey(name)
&& x["name"] != "aa")).FirstOrDefault();

How to use dictionary with dynamic value? [duplicate]

I have below code in C#
Dictionary<string, object> dObject = new Dictionary<string, object>();
I want to convert dObject to Dictionary<string, string>. How can I do this?
Use the ToDictionary method:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());
Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.
If your dictionary can contain null values you should add a null check before performing the ToString:
Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());
The reason this works is that the Dictionary<string, object> is actually an IEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.
Edit:
In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}
Edit2:
If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:
Dictionary<string, string> sd = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}
.NET 3.5:
Dictionary<string, string> result = dObject.ToDictionary(kvp => kvp.Key, kvp => Convert.ToString(kvp.Value));
.NET 2.0:
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> kvp in dObject) result.Add(kvp.Key, Convert.ToString(kvp.Value));
Since you are using .net 2.0:
Dictionary<string, string> dString = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> item in dObject)
{
dString.Add(item.Key, item.Value.ToString());
//here item.Value.ToString() is an example
//you should convert your item to string according to the requirement
}
How about:
Dictionary<string, string> newDictionary = dObject.ToDictionary(k => k.Key, k => (string) k.Value);
In .Net 2.0 probably your best friend is foreach loop:
Dictionary<string, object> dObject = new Dictionary<string, object>();
Dictionary<string, string> newObjects = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> keyValuePair in dObject)
{
newObjects.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}
Dictionary<string, string> dString = dObject.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString());
It's just idea. You can insert any verifications.

Compare two dictionaries and merge in to other dictionary with keys and values present in both dictionaries

I am working on small utility and as it turns out I have to compare two dictionaries and export the data in Excel in the below format
Key dict1value dict2value
If a key is available in both the dictionaries. My output would be
Key dict1value dict2value
If a key is available in firstdictionary and not in second . My output would be
Key dict1Value "NotAvailable"
If a key is available in second dictionary but not in first . My output would be
key "Not Available" dict2value.
To be more clear, The key column in Excel consists of keys from both the dictionaries.The value columns will have values depending on the availability.
Though the below code is working,I would like to know if I can optimize the performance even more.
Note : Please ignore the bad naming conventions
public void validateTwoDictionaries()
{
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
Dictionary<string, KeyValuePair<string, string>> complexdicts = new Dictionary<string, KeyValuePair<string, string>>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
int count1 = dict1.Keys.Count;
int count2 = dict2.Keys.Count;
int maxcount = count2;
if (count1 > count2)
{
maxcount = count1;
}
for (int i = 0; i < maxcount; i++)
{
string dict1Key = string.Empty; string dict2Key = string.Empty;
//need to iterate both the dictionaries at one go.
if (i < count1)
{
dict1Key = dict1.Keys.ElementAt(i);
}
if (i < count2)
{
dict2Key = dict2.Keys.ElementAt(i);
}
// do the work for first dictionary, try to decouple to reuse for the 2nd dict
if (dict1Key != string.Empty)
{
if (!complexdicts.Keys.Contains(dict1Key))
{
if (dict2.Keys.Contains(dict1Key))
{
// Add to the complext dictionary
complexdicts.Add(dict1Key, new KeyValuePair<string, string>(dict1[dict1Key], dict2[dict1Key]));
}
else
{
complexdicts.Add(dict1Key, new KeyValuePair<string, string>(dict1[dict1Key], "Not Available"));
}
}
}
// do the work for second dictionary
if (dict2Key != string.Empty)
{
if (!complexdicts.Keys.Contains(dict2Key))
{
if (dict1.Keys.Contains(dict2Key))
{
// Add to the complext dictionary
complexdicts.Add(dict2Key, new KeyValuePair<string, string>(dict1[dict2Key], dict2[dict2Key]));
}
else
{
complexdicts.Add(dict2Key, new KeyValuePair<string, string>("Not Available", dict2[dict2Key]));
}
}
}
}
dict1 and dict2 are sample dictionaries and complexdicts object is what I want to export to excel.
Please let me know if I can do this in better way.
How about this?
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
Dictionary<string, KeyValuePair<string, string>> complexdicts = new Dictionary<string, KeyValuePair<string, string>>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
var allKeys = dict1.Keys.Union(dict2.Keys);
foreach (var key in allKeys)
{
string val1;
if (!dict1.TryGetValue(key, out val1))
{
val1 = "Not Available";
}
string val2;
if (!dict2.TryGetValue(key, out val2))
{
val2 = "Not Available";
}
complexdicts.Add(key, new KeyValuePair<string, string>(val1, val2));
}
How about this?
Dictionary<string, string> dict1 = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict1.Add("A", "1");
dict1.Add("B", "2");
dict2.Add("A", "2");
dict2.Add("C", "3");
dict2.Add("D", "4");
var allKeys = dict1.Keys.Union(dict2.Keys);
// case 1
List<Tuple<string, string, string>> unionValues = new List<Tuple<string, string, string>>();
foreach (var key in allKeys)
{
unionValues.Add(new Tuple<string, string, string>(key, dict1.ContainsKey(key) ? dict1[key] : "N/A" , dict2.ContainsKey(key) ? dict2[key] : "N/A"));
}
// case 2
var result = (from key in allKeys
select new Tuple<string, string, string>(key, dict1.ContainsKey(key) ? dict1[key] : "N/A", dict2.ContainsKey(key) ? dict2[key] : "N/A")).ToList();

How to add items to a dictionary that contains a dictionary within

I want to add items to a dictionary that contains a dictionary within please refer the code below.
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// I have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID,item.Name,item.Score);
}
I guess Tuple<string, string, int> is the best suit for your case, not Dictionary:
var list = TrainingCourseList
.Select(item => Tuple.Create(item.ID, item.Name, item.Score));
if you want to add an entry to the outer dictionary you have to do something like
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// i have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID,new Dictionary<string,int>{{item.Name,item.Score}};
}
Try
Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
// i have to add item.ID,item.Name,item.Score something like below
dict.Add(item.ID, new Dictionary<string, int> { item.Name, item.Score });
}

How do I copy the content of a dictionary to an new dictionary in C#?

How can I copy a Dictionary<string, string> to another new Dictionary<string, string> so that they are not the same object?
Assuming you mean you want them to be individual objects, and not references to the same object pass the source dictionary into the destination's constructor:
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = new Dictionary<string, string>(d);
"so that they are not the same object."
Ambiguity abound - if you do actually want them to be references to the same object:
Dictionary<string, string> d = new Dictionary<string, string>();
Dictionary<string, string> d2 = d;
(Changing either d or d2 after the above will affect both)
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> first = new Dictionary<string, string>()
{
{"1", "One"},
{"2", "Two"},
{"3", "Three"},
{"4", "Four"},
{"5", "Five"},
{"6", "Six"},
{"7", "Seven"},
{"8", "Eight"},
{"9", "Nine"},
{"0", "Zero"}
};
Dictionary<string, string> second = new Dictionary<string, string>();
foreach (string key in first.Keys)
{
second.Add(key, first[key]);
}
first["1"] = "newone";
Console.WriteLine(second["1"]);
}
}
A one-line version of Amal's answer:
var second = first.Keys.ToDictionary(_ => _, _ => first[_]);

Categories

Resources