C# 数组转json
////////试题信息///////////////// // 已知 // h、d两个数组分别表示表头和内容 // 要求 // 编写函数一:rs2Array // 返回一个数组,每一项为一个对象。 // 编写函数二:rs2MultiHash // 返回一个对象,内容是键值对。 //////////////////////////////// using System; using System.Collections.Generic; public class test_02_quiz { static void Main(string[] args) { List<String> tmp, h = new List<String>(); h.Add("id"); h.Add("name"); h.Add("region"); List<List<String>> d = new List<List<String>>(); tmp = new List<String>(); tmp.Add("100"); tmp.Add("wang"); tmp.Add("shanghai"); d.Add(tmp); tmp = new List<String>(); tmp.Add("101"); tmp.Add("huang"); tmp.Add("beijing"); d.Add(tmp); tmp = new List<String>(); tmp.Add("102"); tmp.Add("zhang"); tmp.Add("beijing"); d.Add(tmp); tmp = new List<String>(); tmp.Add("103"); tmp.Add("wang"); tmp.Add("shanghai"); d.Add(tmp); String str1 = rs2Array(h, d); Console.WriteLine(str1); String str2 = rs2MultiHash(h, d, h[2]); Console.WriteLine(str2); } /* rs2Array(h, d) 期望结果为: [ {id: "100", name: "wang", region: "shanghai"}, {id: "101", name: "huang", region: "beijing"}, {id: "102", name: "zhang", region: "beijing"}, {id: "103", name: "li", region: "shanghai"} ] */ private static String rs2Array(List<String> h, List<List<String>> d) { //return "not implemented"; // 注释上面一句,并请在此实现函数: } /* rs2MultiHash(h, d, h[0]) 期望结果为: { "100": [{id: "100", name: "wang", region: "shanghai"}], "101": [{id: "101", name: "huang", region: "beijing"}], "102": [{id: "102", name: "zhang", region: "beijing"}], "103": [{id: "103", name: "li", region: "shanghai"}] } */ /* rs2MultiHash(h, d, h[2]) 期望结果为: { "shanghai": [ {id: "100", name: "wang", region: "shanghai"}, {id: "103", name: "li", region: "shanghai"} ], "beijing": [ {id: "101", name: "huang", region: "beijing"}, {id: "102", name: "zhang", region: "beijing"} ] } */ private static String rs2MultiHash(List<String> h, List<List<String>> d, String key) { //return "not implemented"; // 注释上面一句,并请在此实现函数: } // 如果有公共函数需要提取,请在此编写: }
方法代码:
private static String rs2Array(List<String> h, List<List<String>> d) { return JsonConvert.SerializeObject(d.Select(x => middleConvert(h, x))); } private static String rs2MultiHash(List<String> h, List<List<String>> d, String key) { return JsonConvert.SerializeObject(d.Select(x => middleConvert(h, x)) .GroupBy(x => x[key]) .ToDictionary(x => x.Key, x => x.ToArray())); } private static Dictionary<string, string> middleConvert(List<string> h, List<string> d) { return h.ToDictionary(x => x, x => d[h.IndexOf(x)]); }