2016-12-03 35 views
-2

我有一個包含類似這樣的項目的列表:重組列表項成組

{ 
Answer: "test answer", 
FaqTopicName :"General", 
Question: "test question", 
SortOrder: 0 
}, 

{ 
Answer: "...", 
FaqTopicName :"General", 
Question: "...", 
SortOrder: 1 
}, 

... (repeated) 

我希望改組名單,以便它現在包含一個對象的內部分組每個列表項目。結果對象將如下所示,並將包含屬性名稱爲「items」= []下具有相同FaqTopicName的所有項目。

數據我希望進行最後的格式爲:

{ 
    topicName: "General", 
    items: { 
     Answer: "test answer", 
     Question: "test question", 
     SortOrder: 0 
     }, 
     { 
     Answer: "...", 
     Question: "...", 
     SortOrder: 1 
     } 
} 

以下是我已經試過了,但它不出來正確的,也不會通過JavaScriptSerializer()運行:

List<FaqQuestionAnswer> allFaqItemsInSelectedSytem = faqController.GetAllFaqItemsForSystem(out errors); 

var groupedData = (from qaItem in allFaqItemsInSelectedSytem 
        group qaItem by qaItem.FaqTopicName 
        into questionsAnswersGroupedDataset 
          select questionsAnswersGroupedDataset).Distinct().ToDictionary(items => new { title = items.Key.ToString(), items = items.ToList() }); 

在調試器在此所得到的:

[0] = {[{標題=電子書,項= System.Collections.Generic.List 1[JPay.Base.FaqQuestionAnswer] }, System.Linq.Lookup 2 +分組[System.String,JPay.Base.FaqQuesti onAnswer]]}

但是當我通過JSON轉換器運行它拋出鍵入錯誤:

類型「System.Collections.Generic.Dictionary 2[[<>f__AnonymousType0 -2 - [[System.String,mscorlib程序,版本= 4.0.0.0 ,Culture = neutral,PublicKeyToken = XXXXXXXXXXX],[System.Collections.Generic.List 1[[Base.FaqQuestionAnswer, Version=1.0.6180.30742, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXX]], tttwebsite, Version=1.0.6181.25360, Culture=neutral, PublicKeyToken=null],[System.Linq.IGrouping 2 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = XXXXXXXXXXXXX],[ttt.Base.FaqQuestionAnswer, tttBase,Version = 1.0.6180.30742,Culture = neutral,PublicKeyToken = null]],System.Core,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = XXXXXXXXXXXXXXXXX]]不支持字典序列化/反序列化,必須是字符串或對象。

感謝您的幫助。

+0

當你說「它沒有出來正確」時,你得到的數據格式是什麼? –

回答

0

主要的問題是在這裏:

.ToDictionary(items => new { title = items.Key.ToString(), items = items.ToList() }); 

你可能覺得要定義Key = items.Key.ToString()Value = items.ToList()一本字典,但實際上ToDictionaryoverload您使用具有以下特徵:

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
    this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector 
) 

因此您將結果轉換爲一些奇怪的字典,其中匿名類型爲{ string title, IEnumerable<FaqQuestionAnswer> items }作爲鍵,IGrouping<string, IEnumerable<FaqQuestionAnswer>>作爲值。

如果你真的需要字典,那麼你應該使用this overload代替:

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
    this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector, 
    Func<TSource, TElement> elementSelector 
) 

這樣的:

.ToDictionary(g => g.Key, g => g.ToList()); 

還要注意的是DistictGroupBy是多餘的。

爲了得到你所描述的確切格式,你可以使用簡單的GroupBy定製Select

var groupedData = allFaqItemsInSelectedSytem 
    .GroupBy(e => e.FaqTopicName) 
    .Select(g => new 
    { 
     topicName = g.Key, 
     items = g.Select(e => new { e.Answer, e.Question, e.SortOrder }).ToList() 
    }).ToList(); 

,或者如果你喜歡查詢語法:

var groupedData = 
    (from e in allFaqItemsInSelectedSytem 
    group e by e.FaqTopicName into g 
    select new 
    { 
     topicName = g.Key, 
     items = (from e in g select new { e.Answer, e.Question, e.SortOrder }).ToList() 
    }).ToList(); 
+0

嗨,謝謝你的幫助。我無法將結果轉換爲JSON,似乎仍然有這樣的問題 –

0

我結束了這一點,這給了我需要的結果:

protected string GetJPayWebsiteFaqTopics() 
    { 
     // call the FAQ manager 
     var faqController = managers.GetFaqManager(); 
     string errors = string.Empty; 
     string result = string.Empty; 

     // All items returned from faq manager, 2d collection not grouped into topic dictionaries 
     List<FaqQuestionAnswer> allFaqItemsInSelectedSystem = faqController.GetAllFaqItemsForSystem(out errors); 

     // Storage for main data, prior to serialization 
     List<Dictionary<string, object>> allFaqTopicsAndItems = new List<Dictionary<string, object>>(); 

     // Group all item Lists together in alike topic related faq items 
     IEnumerable<IGrouping<string, FaqQuestionAnswer>> groupedData = from qaItem in allFaqItemsInSelectedSystem 
                     group qaItem by qaItem.FaqTopicName; 
     // Allow the groupData to get iterated 
     IGrouping<string, FaqQuestionAnswer>[] enumerableGroups = groupedData as IGrouping<string, FaqQuestionAnswer>[] ?? groupedData.ToArray(); 
     JavaScriptSerializer jsonConverter = new JavaScriptSerializer(); 

     foreach (var instance in enumerableGroups) 
     { 
      // Each group of data should have a title for the group, a list of FAQ items 
      var items = instance.ToList(); 

      // Temp storage for each topic and associated faq item data 
      Dictionary<string, object> group = new Dictionary<string, object>(); 

      /** 
      * Temp storage for clean faq items stripped of topic level data which has now 
      * been added to the parent node so no longer needed at this level 
      */ 
      List<QuestionAnswerOrderOnly> cleanedItems = new List<QuestionAnswerOrderOnly>(); 

      // Add the group title 
      group.Add("Title", instance.Key); 

      // Add the topics display order to the group data 1st item since it is on every item 
      group.Add("TopicOrder", items[0].TopicOrder); 

      /** 
      * Pull the values that are important for the item only, add it to the group 
      * Clean up item before recording it to the group it belongs to 
      */ 
      cleanedItems.AddRange(items.Select(item => new QuestionAnswerOrderOnly(item.Question, item.Answer, item.ItemOrder))); 

      // Add the clean faqitems collection 
      group.Add("Items", cleanedItems); 

      // Add this topic group to the result 
      allFaqTopicsAndItems.Add(group); 
     } 

     jsonConverter.MaxJsonLength = Int32.MaxValue; 

     try 
     { 
      result = jsonConverter.Serialize(allFaqTopicsAndItems); 
     } 
     catch (Exception error) 
     { 
      result = $"{errors} {error.Message}"; 
     } 

     return result; 
    } 

並輸出如下:

{ 
    topicName: "General", 
    items: { 
     Answer: "test answer", 
     Question: "test question", 
     SortOrder: 0 
     }, 
     { 
     Answer: "...", 
     Question: "...", 
     SortOrder: 1 
     } 
} 

我希望這可以幫助處於類似情況的其他人。