How to join and perform an operation between JSON data in C#? -
i'm dealing linq-to-entities, querying 2 different entities. 1 returns data
, other returns addvalues
, have references both newtonsoft.json
, system.data.objets
: var query1
returns data
, var query2
returns addvalues
. debugging can see that:
data = [{"key":"tf","value":221},{"key":"ba","value":108}]; addvalues = [{"key":"tf","value":2},{"key":"ba","value":1.5}];
how obtain new string/object joining "key" , performing operation between values data , addvalues? result of query should calculatedresult
.
result = [{"key":"tf","value":221+2},{"key":"ba","value":108+1.5}]; calculatedresult = [{"key":"tf","value":223},{"key":"ba","value":109.5}];
important note: can sure both arrays have same number of items, not ordered key
the following snippet work, assuming each element in data
, addvalues
has both key
, value
field.
public class foo { public string key; public float value; } class program { static void main(string[] args) { var data = "[{\"key\":\"tf\",\"value\":221},{\"key\":\"ba\",\"value\":108}]"; var addvalue = "[{\"key\":\"tf\",\"value\":2},{\"key\":\"ba\",\"value\":1.5}]"; var obj1 = jsonconvert.deserializeobject<list<foo>>(data); var obj2 = jsonconvert.deserializeobject<list<foo>>(addvalue); var new_obj = (from in obj1 b in obj2 a.key == b.key select new foo { key = a.key, value = a.value + b.value }).tolist(); console.writeline(jsonconvert.serializeobject(new_obj, formatting.indented)); } }
output:
[ { "key": "tf", "value": 223.0 }, { "key": "ba", "value": 109.5 } ]
Comments
Post a Comment