Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
In PHP and Python I can deserialise a JSON document to a dictionary structure. That's the default behaviour and there are not many other options anyway. In C#, hovever, all is typed and System.Text.Json methods want to know what type to deserialise into. Since I don't know the structure of the JSON document and just need to pass it on to something that can handle a dictionary, I need to convert it to that.
This doesn't work as expected:
var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>("{ \"a\": 1, \"b\": { \"c\": 3 } }");
At least what the VSCode debugger shows me, I have a dictionary with the keys "a" and "b" but the values are anything. I'd expect to see an int as value for "a" and another Dictionary as value for "b" with an int for the value "c".
How can this be achieved?
I'm looking for something like this:
// Does not exist:
var dict = System.Text.Json.JsonSerializer.DeserializeToDictionary("{ \"a\": 1, \"b\": { \"c\": 3 } }");
I'm trying to convert a class that I've written in Python because I hit other roadblocks in Python. I'm more experienced in C# so I'd like to solve the problem there, but JSON for dynamic data isn't a strength of C#. Seems I have to write some classes of my application in Python and others in C# to get it done.
Newtonsoft.Json fits much better for the complicated cases. You can try this code
using Newtonsoft.Json;
var jsonParsed = JObject.Parse(json);
var dict = new Dictionary<string, object>();
AddDictionaries(dict,jsonParsed);
public void AddDictionaries(Dictionary<string, object> dict, JObject jsonObj)
{
foreach (var prop in jsonObj)
{
if (prop.Value.Type != JTokenType.Object)
dict.Add(prop.Key, prop.Value);
else
{
var nestedDict = new Dictionary<string, object>();
AddDictionaries(nestedDict, (JObject)prop.Value);
dict.Add(prop.Key, nestedDict);
}
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So i have a let's say 100 statements in C#.
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU01_IEmergOpenAct.Force(false);
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU02_IEmergOpenAct.Force(false);
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU03_IEmergOpenAct.Force(false);
And so on till DCU100. I want to run a loop in that way that I can access all the statements DCU01..DCU100.
EDIT : Everything before Force. is a signal container. That's why can't use Array or List (No overload method).
You can use reflection
var obj = CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst;
for(int i = 0; i < yourCount; i++){
var prop = obj.GetType().GetProperties().FirstOrDefault(x => x.Name == string.Format("DCU{0}_IEmergOpenAct", i));
if(prop != null){
var propValue = (YourObjectType)prop.GetValue(CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst);
propValue.Force(False);
}
}
Maybe you need to format the i variable to "00" or something in the string.Format() call
If CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU01_IEmergOpenAct is a type name (instead of a member), then you can try the following approach:
IEnumerable<MethodInfo> methods =
Enumerable.Range(1, 100)
.Select(i => $"CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU{i:D2}_IEmergOpenAct")
.Select(t => Type.GetType(t))
.Select(t => t.GetMethod("Force", BindingFlags.Public | BindingFlags.Static));
foreach (MethodInfo force in methods)
force.Invoke(null, new object[] { false });
Option 1
Useful if you don't mind writing the whole list once and need it multiple times.
Put it into all individual items into a List/Array and loop over it.
var list = new List<IEmergOpenAct>() { // I am guessing a type here
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU01_IEmergOpenAct,
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU02_IEmergOpenAct,
CCU_O.MWT.DRSa09_DrEmrgOpn.DRSa09_DrEmrgOpnCst.DCU03_IEmergOpenAct,
};
foreach (var act in list)
{
act.Force(false);
}
Option 2
Useful if you don't want to type the whole list but they follow a unique pattern.
Open the Type/Namespace DRSa09_DrEmrgOpnCst via Reflection and get all Types that match the "DCU??_IEmergOpenAct" pattern. Put them into a list like in option 1 and loop over them as shown above.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have one original list and two temporary lists.
Based on certain condition, I am adding data from the original list(after modifying certain values) to these temp lists. But changes made in one temp list via this copy operation is updating the other temp list as well.
List<UserLMSSubFunc> lstUserLMSSubFunc = null;
List<UserLMSSubFunc> lstUserLMSSubFuncTemp1 = new List<UserLMSSubFunc>();
List<UserLMSSubFunc> lstUserLMSSubFuncTemp2 = new List<UserLMSSubFunc>();
foreach (Constructor subFnc in originalList)
{
foreach (KeyValuePair<string, string> kv in OriginalList)
{
if (kv.Value.ToUpper() == subFnc.SubFuncCode.ToUpper())
{
if (subFnc.FuncCode == null)
{
subFnc.FuncCode = kv.Key;
templist1.Add(subFnc);
}
else
{
subFnc.FuncCode = kv.Key;
Templist2.Add(subFnc);
}
}
}
}
The reason why the data in your lists is changing is due to the reference / value type mishmash. Your lists hold only a reference to an object inside that list. Therefore whenever you change your object which you have pulled from one of the lists I suspect it is the same object which is located in the other two as well, hence the change which seemingly propagates itself across the lists.
Use Setter
private var temp1 = new List<Package>();
public List<Package> temp1
{
set { temp1 = value;
update your temp2}
get { return temp1; }
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a problem with the algorithm Fisher in c#.
I have a class system of SystemDecyzyjny. In it I have a dictionary.
public Dictionary<int, Dictionary<int, double>> posortowane = new Dictionary<int, Dictionary<int, double>>();
Data in dictionary:
How to display with posortowane data in Form1.cs in this form:
2 4 1 3
. . . .
. . . .
How to refer to the dictionary and display data from it attributes?
If you want to access the value of the key 0, then you just write this:
posortowane[0]
This returns a Dictionary<int, double>.
Now you can read the value with key 0 of the latter dictionary as:
posortowane[0][0]
The value with the key 1 as:
posortowane[0][1]
and so on and so forth.
It sounds like you want to print out all keys of the inner dictionary. This can be done in the following way:
foreach (var outerKey in posortowane.Keys)
{
foreach (var inner in posortowane[outerKey])
{
Console.WriteLine(inner.Key);
}
}
If you want to print out the both the keys and values of the inner dictionary you could do:
foreach (var outerKey in posortowane.Keys)
{
foreach (var inner in posortowane[outerKey])
{
Console.WriteLine($"{inner.Key}:{inner.Value}");
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having a return type of a function being set to IEnumerable<Dictionary<string, object>> and I need to get the key, value pairs.
Using the appropriate key, I need to change the value.
I have a solution when the return type is a Dictionary but not when IEnumerable<Dictionary<string, object>>
I finally need to modify the value after, the specific key is found.
These following solutions maybe what your looking for, However you'll have to work out which one is more appropriate based on your circumstances
Given
var myKey = "someKey";
Assuming, your list of dictionaries contains the key your looking for, only once
var aDictionary = MyEnumerable.Single(x => x.ContainsKey(myKey));
aDictionary[myKey] = myNewValue;
An InvalidOperationException will be thrown if
More than one key is found
No keys are found
Assuming your list of dictionaries may or may not contain the key your looking for, only once
var aDictionary = MyEnumerable.SingleOrDefault(x => x.ContainsKey(myKey));
if(aDictionary != null)
{
aDictionary[myKey] = myNewValue;
}
An InvalidOperationException will be thrown if
More than one key is found
Assuming there may be multiple occurrences of your key
foreach (var aDictionary in MyEnumerable.Where(x => x.ContainsKey(myKey)))
{
aDictionary[myKey] = myNewValue;
}
Update
It seems you might be confused with the type IEnumerable<Dictionary<string, object>>
IEnumerable is a list (for the point of this conversation)
A Dictionary represents a collection of keys and values.
So what you have is a list of collections of keys and values
You can iterate through the IEnumerable> using a foreach sentence:
(this is just an example to help to illustrate)
IEnumerable<Dictionary<string, object>> colectionDict;
foreach(var dict in colectionDict) //dict is an object of type Dictionary<string,object>
Also, you can use a variable type Enumerator.
var enum = colectionDict.GetEnumerator();
while(enum.Next){
var dict = enum.Current; // dict is an object of type Dictionary<string,object>
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I understand, that it sounds a little bit strange, but I use triple nested dictionary in my program. It is the most suitable form for my data representation.
Code sample:
Dictionary<string, IDictionary> outerDictionary;
Dictionary<string, IDictionary> middleDictionary;
Dictionary<string, string> innerDictionary;
As you can suspect from names : innerDictionary is "Value" of middleDictionary and middleDictionary is "Value" of outerDictionary;
And I am trying to iterate through it, I need to get values from the inner Dictionary. I think I got stucked with this simple task.
Would really appreciate any help.
Thanks in advance.
PS > Thanks a lot for all your help!
If you just want a flat list of all values, you can do that with a chained SelectMany:
outerDictionary.SelectMany(d => d.Value) // middle Dictinoary
.SelectMany(d => d.Value)
.Select(kvp => kvp.Value); // inner Dictionary
Brute force:
foreach(KeyValuePair<string, IDictionary> entryOuter in outerDictionary)
{
foreach(KeyValuePair<string, IDictionary> entryMiddle in entryOuter.Value)
{
foreach(KeyValuePair<string, string> entry in entryMiddle.Value)
{
// do something with entry.Value
}
}
}
If your outerDictionary is declared like this
Dictionary<string,Dictionary<string,Dictionary<string,string>>> outerDictionary;
you can iterate the innermost values like this:
var innermost = outerDictionary.Values
.SelectMany(v1 => v1.Values.SelectMany(v2 => v2.Values));
If for some reason you are using non-generic dictionaries, but you are on .NET 3.5 or later, you fix this by adding a call to Cast<>, like this:
var innermost = outerDictionary.Values.Cast<Dictionary<string,Dictionary<string,string>>>
.SelectMany(v1 => v1.Values.SelectMany(v2 => v2.Values));
As described in the documentation, the Values property is an enumeration of all values contained; so you could use
foreach ( var middleDictionary in outerDictionary.Values )
{
foreach ( var innerDictionary in outerDictionary.Values )
{
foreach ( string iString in innerDictionary.Values )
{
// your code
}
}
}
You should probably be using a different data structure that's easier to think about than tripledecker Dictionaries. Even if you don't, you should definitely use typed Dictionaries:
Dictionary<string, Dictionary<string, Dictionary<string, string>>> TripleDictionary;
You can then itereate throgh them like so:
foreach (KeyValuePair<string, IDictionary> first in TripleDictionary)
{
foreach (KeyValuePair<string, IDictionary> second in first.Value)
{
foreach (KeyValuePair<string, string> third in second.Value)
{
string x = third.Value;
// Do stuff
}
}
}
Implicit types will make it more readable:
foreach (var first in TripleDictionary)
{
foreach (var second in first.Value)
{
foreach (var third in second.Value)
{
string x = third.Value;
// Do stuff
}
}
}