使用LINQ在JSON中创建树层次结构

时间:2010-06-30 21:48:12

标签: c# linq json

我有一个随机顺序的名单的平面列表。是否可以编写单个LINQ语句来在JSON中创建树层次结构,以便根据以下示例说明的规则对它们进行分组:

输入:

"Banana", "Apple", "Cheery", "Lemon", "Orange", ...

输出:

{
    "A, B, C": "Apple, Banana, Cherry",
    "D, E, F" : "",
    ...
    "J, L, M": "Lemon",
    "N, O, P": "Orange",
    ...
}

2 个答案:

答案 0 :(得分:9)

var list = new[] { "Banana", "Apple", "Cheery", "Lemon", "Orange" };

var js = new JObject(from y in Enumerable.Range(0, 9)
                     join x in list
                     on y equals (x[0] - 'A') / 3
                     into g
                     let k = string.Join(", ", from i in Enumerable.Range(0, 3)
                                               select (char)(3 * y + i + 'A'))
                     let v = string.Join(", ", from s in g orderby s select s)
                     select new JProperty(k, new JValue(v)));

输出:

{
  "A, B, C": "Apple, Banana, Cheery",
  "D, E, F": "",
  "G, H, I": "",
  "J, K, L": "Lemon",
  "M, N, O": "Orange",
  "P, Q, R": "",
  "S, T, U": "",
  "V, W, X": "",
  "Y, Z, [": ""
}

答案 1 :(得分:1)

基本的查询结构是这样的:

// sample data.....
char[][] rules = new char[2][];
rules[0] = new char[] { 'A', 'B', 'C' };
rules[1] = new char[] { 'D', 'E', 'F' };
string[] rawData = new string[] { "Apple", "Fig", "Daikon", "Bing Cherry" };

// query....
var results = from rule in rules
              select new
              {
                  Rule = rule,
                  Matches = (from word in rawData
                              join initialchar in rule on word[0] equals initialchar
                              select word)
              };

之后格式化为JSON应该很简单。