I have the following dictionary sample, and ideally what I'd like to do (just once at a certain point) is end up with the groupTotals being the sum of each "time" value where the key (eg 98154646703) appears in multiple "group" values. So, for example:
The first two items below would have a groupTotal of 960 because 98154646703 appears in both the first and second item's "group" value. The next three would have a groupTotal of 82,260 etc.
I can make my way around dictionaries but this is a little too complex for my brain at the moment I'm afraid! Hopefully this all makes sense and there's a way to do it?
{
"_testList": {
"98154646703": {
"time": 180.0,
"group": "98154646703, 98149569526"
"groupTotal": 0
},
"98149569526": {
"time": 780.0,
"group": "98149569526, 98154646703"
"groupTotal": 0
},
"98863457238": {
"time": 81480.0,
"group": "98979117899, 97989042539, 98863457238"
"groupTotal": 0
},
"97989042539": {
"time": 390.0,
"group": "98979117899, 98863457238, 97989042539"
"groupTotal": 0
},
"98979117899": {
"time": 390.0,
"group": "98979117899, 98863457238, 97989042539"
"groupTotal": 0
}
CodePudding user response:
This should be fairly trivial using a dictionary. Something like:
var dict = _testList.ToDictionary(i => i.Key, i => i);
foreach(var item in dict.Values){
var groupTotal = item.Group.Sum(g => dict[g.Key].Time);
// Use group total in some way
}
This of course assumes you have an appropriate c# type and deserialized your json to a list of that type. I.e. Something like
public class MyClass{
public string Key {get;set;}
public double Time {get;set;}
public List<string> Group {get;set;}
public double GroupTotal {get;set;}
}
CodePudding user response:
You need to split groups in an array/list and then treat each of value of this list as a key to _testList.
public class Root
{
public Dictionary<string, Data> _testList { get; set; }
}
public class Data
{
public double time { get; set; }
public string group { get; set; }
public double groupTotal { get; set; }
}
static void Main(string[] args)
{
string json = "{\"_testList\":{\"98154646703\":{\"time\":180.0,\"group\":\"98154646703,98149569526\",\"groupTotal\":0},\"98149569526\":{\"time\":780.0,\"group\":\"98149569526,98154646703\",\"groupTotal\":0},\"98863457238\":{\"time\":81480.0,\"group\":\"98979117899,97989042539,98863457238\",\"groupTotal\":0},\"97989042539\":{\"time\":390.0,\"group\":\"98979117899,98863457238,97989042539\",\"groupTotal\":0},\"98979117899\":{\"time\":390.0,\"group\":\"98979117899,98863457238,97989042539\",\"groupTotal\":0}}}";
Root obj = JsonSerializer.Deserialize<Root>(json);
foreach(var item in obj._testList)
{
var groups = item.Value.group.Split(',');
foreach (var group in groups)
{
item.Value.groupTotal = obj._testList[group].time;
}
}
}