I have the following Dictionary
public static Dictionary<string, List<int>> termDocumentIncidenceMatrix = new Dictionary<string, List<int>>();
I want to print all values in it , How i can make it ?
I found KeyValuePair but can't recognize in my program ?
Can anyone give me bit of code or link ?
foreach (var term in termDocumentIncidenceMatrix)
{
// Print the string (your key)
Console.WriteLine(term.Key);
// Print each int in the value
foreach (var i in term.Value)
{
Console.WriteLine(i);
}
}
If you want to print all values of the dictionary, you can use:
Dictionary<string, List<int>> dict = new Dictionary<string,List<int>>{{"A",new List<int>{1,2}},{"B",new List<int>{3,4}}};
var integersList = dict.Values.SelectMany(it => it);
foreach (var item in integersList)
{
Console.WriteLine(item);
}
Related
I'm using a dictionary in my code as follows:
var allValues = new Dictionary<string, int>();
while (//condition))
{
response = // call to a method that returns some values of type Dictionary<string, int>
allValues.Add(response);
}
When I use .Add I get the following error:
What am I missing?
A Dictionary can be iterated over as collection of key/value pairs, so you can do this:
while (condition)
{
response = // call to a method that returns some values of type Dictionary<string, int>
foreach(KeyValuePair<string, int> kvp in response)
{
allValues.Add(kvp.Key, kvp.Value);
}
}
Assuming response is itself a Dictionary
You can add key value pair to dictionary. Try below code as an example.
var allValues = new Dictionary<string, int>();
int diccounter = 0;
while (true)
{
allValues.Add("a" + diccounter, diccounter++);
}
I'm trying to build this datastructure with a nested dictionary:
["A",["A",123]],
["B",["B",123]],
["C",["C",123]],
And then loop over the data structure and print out the values.
The first problem is, that all the nested dictionaries are the same {"C",123}.
I think it's because it is the same object, but I don't know how to overcome that. Can I dynamically create new objects in the loop ?
The other problem i face is in the loop where I try to print out the Values.
The compiler says that it can't convert Dictionary to Dictionary.
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
List<string> liste = new() { "A", "B", "C" };
Dictionary<string, Dictionary<string, int>> DictOfDicts = new();
Dictionary<string, int> DictOfData = new();
foreach (string i in liste)
{
DictOfData.Clear();
DictOfData.Add(i, 123);
DictOfDicts.Add(i, DictOfData);
}
foreach (Dictionary<string, int> i in DictOfDicts)
{
Console.WriteLine("Some result");
}
}
}
}
You declared DictOfData outside of the foreach loop. Then, all the operations inside the loop are done on the same object. So, you are clearing and filling the same dictionary object over and over again, on each loop iteration.
Just move you declaration of DictOfData to inside the loop, and you'll be good to go.
Bonus:
The whole operation you displayed in the questions can be done with just this:
liste.ToDictionary(x => x, x => new Dictionary<string, int>() { { x, 123 } })
var liste = new List<string>() { "A", "B", "C" };
var DictOfDicts = new Dictionary<string, Dictionary<string, int>>();
foreach (var i in liste)
{
// Create here a new DictOfData to add it to DicOfCicts.
var DictOfData = new Dictionary<string, int>();
DictOfData.Add(i, 123);
DictOfDicts.Add(i, DictOfData);
}
The structure of DicOfDicts is,
["A",["A",123]],
["B",["B",123]],
["C",["C",123]],
I've used a slightly older C# language specification for the answer, and made the type declarations more clear for you to understand.
List<string> list = new List<string>() { "A", "B", "C" };
Dictionary<string, Dictionary<string, int>> parent = new Dictionary<string, Dictionary<string, int>>();
foreach (string i in list)
{
Dictionary<string, int> child = new Dictionary<string, int>();
child.Add(i, 123);
parent.Add(i, child);
}
foreach (KeyValuePair<string, Dictionary<string, int>> parentPair in parent)
{
Dictionary<string, int> childDictionary = parentPair.Value;
foreach (var childPair in childDictionary)
{
Console.WriteLine(childPair.Value);
}
}
It's a very easy exercise to fix your code. Simply replace the DictOfData.Clear(); with the declaration of DictOfData itself. In other words, move the line Dictionary<string, int> DictOfData = new(); into the loop. That way you have a fresh instance of the nested dictionary rather than reusing the old one.
Try this code:
List<string> liste = new() { "A", "B", "C" };
Dictionary<string, Dictionary<string, int>> DictOfDicts = new();
foreach (string i in liste)
{
Dictionary<string, int> DictOfData = new();
DictOfData.Add(i, 123);
DictOfDicts.Add(i, DictOfData);
}
foreach (KeyValuePair<string, Dictionary<string, int>> i in DictOfDicts)
{
Console.WriteLine($"[{i.Key},{String.Join(",", i.Value.Select(x => $"[{x.Key},{x.Value}]"))}]");
}
I have dictionary variable is like:
Dictionary<string,object> dictionary;
This dictionary has nested dictionaries inside in runtime like:
Dictionary<string,Dictionary<string,Dictionary<....<Dictionary<string,int>>>
I am trying to search for all the keys in these nested dictionaries. It may be possible with recursive but i coudn't handle the recursive case. After string comparisons(string.Contains("searchText") done i am going to keep only contained ones.
How can i achieve this goal?
You can try dfs.. Below code just prints every key
public void NestedDictIteration(Dictionary<string,object> nestedDict)
{
foreach (string key in nestedDict.Keys)
{
Console.WriteLine(key);
object nextLevel = nestedDict[key];
if(nextLevel == null)
{
continue;
}
NestedDictIteration((Dictionary<string, object>)nextLevel);
}
}
You can do like this.
Dictionary<string, Dictionary<string, string>> dict= new Dictionary<string, Dictionary<string, string>>();
var query = from outer in dict
from inner in outer.Value
select outer.Key + "->>" + inner.Key + ", " + inner.Value;
foreach (string item in query)
{
//item
}
Or like this
foreach (string key in dict.Keys)
{
foreach (string innerKey in dict[key].Keys)
{
//dict[key][innerKey];
}
}
I'm working with Open XML & I have a IDictionary<String, List<OpenXmlCompositeElement>> structure. I want to work with the List part of the structure but this.map.Values tries to wrap it in an ICollection. How can I get the List part from my structure?
public List<OpenXmlCompositeElement> MapData()
{
//this does not work
return this.map.Values;
}
Since it is a dictionary, it expects you to tell from which key you want the value.
So this would be the code you need, where yourKey is the key you want to retrieve:
public List<OpenXmlCompositeElement> MapData()
{
return this.map["yourKey"];
}
If you have no interest in the key, and the dictionary is just a dictionary because the serializer says so, you could get the first item for example like this:
public List<OpenXmlCompositeElement> MapData()
{
return this.map.Values.First();
}
You can either loop through the dictionary and use the value you would like, or access the List directly using the key (in this case it's a string)
IDictionary<String, List<OpenXmlCompositeElement>> myDictionary;
List<OpenXmlCompositeElement> myList = myDictionary["myKey"];
Where myKey is available in the dictionary.
Alternatively you can loop through
foreach (var item in myDictionary)
{
var key = item.Key;
var value = item.Value
// You could then use `key` if you are unsure of what
// items are in the dictionary
}
Assuming this is your dictionary...
IDictionary<string, List<OpenXmlCompositeElement>> items = ...;
Get a specific List by key...
List<OpenXmlCompositeElement> list = items["key"];
Get the first list in the dictionary...
List<OpenXmlCompositeElement> list = items.Values.First();
Concatenate all lists in the dictionary into a single list...
List<OpenXmlCompositeElement> list = items.SelectMany(o => o).ToList();
foreach(KeyValuePair<string, List<OpenXmlCompositeElement>> kvp in IDictionary)
{
string key = kvp.key
List<OpenXmlCompositeElement> list = kvp.Value;
foreach(OpenXmlCompositeElement o in list)
{
Do anything you need to your List here
}
}
I am working with dictionaries as well, so here is a real example that I am currently working with:
foreach(KeyValuePair<string, List<DataRecords>> kvp in vSummaryResults)
{
string sKey = kvp.Key;
List<DataRecords> list = kvp.Value;
string[] vArr = sKey.Split(',');
int iTotalTradedQuant = 0;
double dAvgPrice = 0;
double dSumQuantPrice = 0;
double dQuantPrice = 0;
double dNumClose = 0;
foreach (DataRecords rec in list)
{
if(vSummaryResults.ContainsKey(sKey))
{
iTotalTradedQuant += rec.iQuantity;
dQuantPrice = rec.iQuantity * rec.dInputTradePrice;
dSumQuantPrice += dQuantPrice;
dAvgPrice = dSumQuantPrice / iTotalTradedQuant;
dNumClose = rec.dNumericClosingPrice;
}
else
{
vSummaryResults.Add(sKey, list);
//dNumClose = rec.dNumericClosingPrice;
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> questionDict = new Dictionary<string, List<string>>(); //creating animal dict
List<string> removeKeys = new List<string>(); //so I can remove the keys if need be
questionDict.Add("Does it have whiskers?", "cat");
questionDict.Add("Does it purr?", "cat");
questionDict.Add("Does it bark?", "dog");
while (true)
{
foreach (KeyValuePair<string, string> kvp in questionDict)//checks for each value of kvp in questionDict
{
Console.WriteLine("Computer: {0}", kvp.Key); //prints kvp, or in this instance, the question
string userInput = Console.ReadLine();
if (userInput.ToLower() == "yes") //if yes THEN
{
Console.WriteLine("VAL: {0}", kvp.Value); //writes the value
}
else
{
removeKeys.Add(kvp.Key); //adds the wrong animals to the removeKeys list
}
}
foreach(string rKey in removeKeys)
{
questionDict.Remove(rKey); //removes all the values of rKey in removeKeys from questionDict
}
}
}
}
new Dictionary<string, List<string>>(); is giving me the error. Any help? I'm trying to make my dictionary have more than one value per key, which I am told can only be achieved through List<string>.
Change your declaration to:
Dictionary<string, List<string>> questionDict = new Dictionary<string, List<string>>();
The generic arguments of the variable being assigned to have to match those of what you are instantiating. The type also has to match of course (which it already did). Please make sure to make this correction to other applicable pieces of your code, like your foreach loop definition.
Note, if you like var (and even if you don't, this is one of the better places it can be used) you can just write:
var questionDict = new Dictionary<string, List<string>>();
Which is much shorter, and harder to mess up!