这是我的代码。
var students={data:[{"name":"abc","id":"101","dept_id":"213"},{"name":"abc","id":"101","dept_id":"212"}]};
var departments={data:[{"name":"it","id":"212"},{"name":"csc","id":"213"}]}
我有两个JObject,如students
和departments
。在student中,数组包含基于dept_id
键的dept_name
键值,其值为departments
数组。
我希望输出如下: -
var students={data:[{"name":"abc","id":"101","dept_id":"213","dept_name":"csc"},{"name":"abc","id":"101","dept_id":"212","dept_name":"it"}]};
答案 0 :(得分:0)
1:使用JArray代替JObject:
var students = JArray.Parse("[{ \"name\":\"abc\",\"id\":\"101\",\"dept_id\":\"213\"},{ \"name\":\"abc\",\"id\":\"101\",\"dept_id\":\"212\"}]");
var departments = JArray.Parse("[{ \"name\":\"it\",\"id\":\"212\"},{ \"name\":\"csc\",\"id\":\"213\"}]");
2。加入:
// Method syntax
var joined = students.Join(departments, s => s["dept_id"].Value<string>(),
d => d["id"].Value<string>(),
(s, d) => new { name = s["name"].Value<string>(),
id = s["id"].Value<string>(),
dept_id = s["dept_id"].Value<string>(),
dept_name = d["dept_name"].Value<string>() });
修改:如果每个部门有多名学生。或多个部分。每个学生(或两者),使用 .GroupJoin 代替 .Join。