[英]How to join and perform an operation between JSON data in C#?
I'm dealing with linq-to-entities, querying 2 different entities. 我正在处理linq-to-entities,查询2个不同的实体。 One returns data
and the other returns addValues
, also I have references to both NewtonSoft.Json
and System.Data.Objets
: var query1
returns data
and var query2
returns addValues
. 一个返回data
,另一个返回addValues
,我也同时引用了NewtonSoft.Json
和System.Data.Objets
: var query1
返回data
而var query2
返回addValues
。 Debugging I can see that: 调试我可以看到:
data = [{"key":"tf","value":221},{"key":"ba","value":108}];
addValues = [{"key":"tf","value":2},{"key":"ba","value":1.5}];
How do I obtain a new string/object joining by "key" and performing an operation between the values from data and addValues ? 如何通过“键”获取新的字符串/对象并在data和addValues的值之间执行操作? The result of the query should be calculatedResult
. 查询结果应为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: I can be sure that both arrays will have the same number of items, BUT not ordered by key
重要说明:我可以确定两个数组的项数相同,但不是key
排序的
The following snippet will work, assuming that each element in data
and addValues
has both a key
and value
field. 假设data
和addValues
中的每个元素都具有key
和value
字段,以下代码段将起作用。
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 a in obj1
from b in obj2
where 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
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.