如何在mvc c#中为两个JObject编写连接查询?

时间:2017-08-16 10:36:45

标签: c# linq model-view-controller

这是我的代码。

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,如studentsdepartments。在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"}]};

1 个答案:

答案 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。