2017-06-27 89 views
0

JSON對象這是我的查詢輸出:如何創建帶有重複列值

 Month SARType Count 
     --------------------------- 
     April Data Protection Breach 2 
     April Miscellaneous - Employee Matters/Fraud 1 
     April Miscellaneous - Information Security 2 
     April Miscellaneous - Unusual Calls/Correspondence 1 
     April Theft - Damage/Theft/Lost Company Property 1 
     March Code of Conduct - Disclosure of Password 1 
     March Data Protection Breach 2 
     March Information Security - Phishing/Spear Phishing 1 
     March Miscellaneous - Employee Matters/Fraud 2 
     March Miscellaneous - Information Security 10 
     March Miscellaneous - Unusual Calls/Correspondence 5 

我需要創建amcharts在下面的風格JSON:

var chartData = [{ 
    month: "April", 
    Data Protection Breach: 2, 
    Miscellaneous - Employee Matters/Fraud: 1, 
    Miscellaneous - Information Security: 2, 
    Miscellaneous - Unusual Calls/Correspondence: 1}, 
    { 
    month: "March", 
    Data Protection Breach: 2, 
    Miscellaneous - Employee Matters/Fraud: 1, 
    Miscellaneous - Information Security: 2, 
    Miscellaneous - Unusual Calls/Correspondence: 1}]; 

我不知道如何從查詢結果中排除重複的月份列,並繼續將相應的行作爲參數添加到同一個json對象。我正在使用字符串生成器在我的MVC應用程序中創建一個json。任何幫助將非常可觀!

+1

集團的價值觀來自行的對insode組 – Fabio

+0

我已經在我的查詢中完成了group,如何在代碼中完成它? – Poonam

+0

使用LINQ Expression,您可以使用groupby –

回答

1

有了下面的代碼,你應該得到的字典集合每月,每一個地方都有字典鍵作爲的SARType值和值由`Month`然後創建字典/名稱值Count

var data = 
    yourDataTable.AsEnumerable() 
       .GroupBy(row => row.Field<string>("Month")) 
       .Select(group => 
       { 
        var temp = new Dictionary<string, object> 
        { 
         { "month", group.Key } 
        } 

        foreach(var row in group) 
        { 
         temp.Add(row.Field<string>("SARType"), row.Field<int>("Count")); 
        } 

        return temp; 
       }); 

serializedData = Newtonsoft.Json.JsonConvert.SerializeObject(data);