开发者

Create tree hierarchy in JSON with LINQ

开发者 https://www.devze.com 2023-01-05 12:27 出处:网络
I have a flat list of some names in a random order.Is it possible to write a single LINQ statement to create a tree hierarchy in JSON so that they would be grouped according to the rules illustrated b

I have a flat list of some names in a random order. Is it possible to write a single LINQ statement to create a tree hierarchy in JSON so that they would be grouped according to the rules illustrated by the example below:

Input:

"Banana", "开发者_StackOverflowApple", "Cheery", "Lemon", "Orange", ...

Output:

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


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)));

Output:

{
  "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, [": ""
}


The basic query structure would be something like this:

// 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)
              };

Formatting as JSON should be straightforward after that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号