2010-06-30 144 views
3

我有一個隨機順序的一些名稱的平面列表。是否有可能寫一個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", 
    ... 
} 
+0

是第一個字符總是一個大寫字母? – dtb 2010-06-30 21:59:35

+0

@dtb:如果它變得更容易,那就是了。 – 2010-06-30 23:15:29

回答

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

不錯,幹得好,很棒。 – 2010-07-01 07:19:22

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應該很簡單。

+0

是的,很好的解決方案。 – 2010-07-01 07:20:18