我正在处理linq-to-entities,查询2个不同的实体。一个返回data
,另一个返回addValues
,同时我也引用了NewtonSoft.Json
和System.Data.Objets
:
var query1
返回data
,var query2
返回addValues
。调试我可以看到:
data = [{"key":"tf","value":221},{"key":"ba","value":108}];
addValues = [{"key":"tf","value":2},{"key":"ba","value":1.5}];
如何通过" key" 获取新的字符串/对象加入,并在数据和 addValues的值之间执行操作?
查询结果应为calculatedResult
。
result = [{"key":"tf","value":221+2},{"key":"ba","value":108+1.5}];
calculatedResult = [{"key":"tf","value":223},{"key":"ba","value":109.5}];
重要提示: 我可以确定两个数组的项目数相同,但未按key
排序
答案 0 :(得分:1)
以下代码段将起作用,假设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));
}
}
输出:
[
{
"key": "tf",
"value": 223.0
},
{
"key": "ba",
"value": 109.5
}
]