tags:

views:

55

answers:

2

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", "Apple", "Cheery", "Lemon", "Orange", ...

Output:

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

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.

millerjs
Yes, good solution.
Khnle
+2  A: 
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, [": ""
}
dtb
Nice, well done, awesome.
Khnle