3

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",
    ...
}
2
  • Is the first character always an uppercase letter? Commented Jun 30, 2010 at 21:59
  • @dtb: If it makes it any easier, then it is. Commented Jun 30, 2010 at 23:15

2 Answers 2

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

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, [": ""
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.