я присоединился несколько столов вместе, который производит набор данных, который выглядит следующим образом:список данных Un-расплющить эффективно
GroupName: "Products and Services";
GroupSortOrder: 0
TopicName: "Money Transfer"
TopicOrder: 11
Question: "Money Transfer question 1"
Answer: "Money Transfer answer 1"
ItemOrder: 0
[повторяется в списке для однако многих элементов]
Мое намерение состоит в том, чтобы в конечном итоге с результатом JSON, который выглядит следующим образом:
var jsonResult = [{
title: 'Products and Services',
order: 0,
items: [{
text: 'Money Transfer',
order: 11,
questionsAndAnswers: [{
question: 'Money transfer question 1',
answer: 'Money transfer answer 1',
order: 0
}]
}]
}];
Я попытался кучу вещей, в том числе GroupBy Linq, который незабываемые мгнове К счастью, группирует значение в ключ, а также не может перемещать связанные значения (порядок, элементы) вместе с «именем группы».
Ниже приведена моя самая близкая попытка, которая заканчивается правильными группами и «данными группового уровня», однако каждая группа содержит все темы, и каждая тема имеет все вопросы, а не только те, которые связаны с этим группы и темы «категория».
ОБНОВЛЕНО, БЛИЖЕ К РЕШЕНИЮ
/// <summary>
/// First organizes all FAQ items by topic property, removes topic data by from item level and groups results by topic desc
/// </summary>
/// <param name="allFaqItemsInSelectedSystem">2d collection of all faq items to be restructured.</param>
/// <param name="outErrors">Errors out.</param>
/// <returns>JSON string containing questionAnswer data inside of related topic objects</returns>
public string SortAndRestructureFaqItemsData(List<FAQQuestionAnswer> allFaqItemsInSelectedSystem, out string outErrors)
{
string jsonResult = string.Empty;
string errors = string.Empty;
// Final result, collection of unique groups
List<FAQGroupedTopicsItemsQuestionsAnswers> groupsCollection = new List<FAQGroupedTopicsItemsQuestionsAnswers>();
// Collection for FAQQuestionAnswerOnly.
List<FAQQuestionAnswerOnly> faqItemsForTopic = new List<FAQQuestionAnswerOnly>();
foreach (var faq in allFaqItemsInSelectedSystem)
{
// Get topic name from faq data.
string topicName = faq.TopicName;
// Get group name from faq data.
string groupName = faq.GroupName;
// New temp topic.
FAQTopicsWithItemsResult newTopic = new FAQTopicsWithItemsResult(topicName, faq.TopicOrder, faqItemsForTopic);
// Check if this group exists.
if (groupsCollection.Any(faqGroup => faqGroup.GroupName == faq.GroupName))
{
// Check if the topic exists inside of this group
if (groupsCollection.Any(faqGroup => faqGroup.GroupTopics.Any(faqTopic => faqTopic.Title == topicName)))
{
// Since the and group exists, add the newTopic to it which also contains the first item.
groupsCollection.Find(faqGroup => faqGroup.GroupName == groupName).GroupTopics.Find(faqTopic => faqTopic.Title == topicName).Items.Add(new FAQQuestionAnswerOnly(faq.Question, faq.Answer, faq.ItemOrder));
}
else
{
// Since the group exists but not the topic, add the new topic containing the new item to the matching group.
groupsCollection.Find(faqGroup => faqGroup.GroupName == groupName).GroupTopics.Add(newTopic);
}
}
else
{
// Since this is a new group, add it along with the new topic, and faqItem
groupsCollection.Add(new FAQGroupedTopicsItemsQuestionsAnswers(groupName, faq.GroupSortOrder, new List<FAQTopicsWithItemsResult> { newTopic }));
}
}
try
{
jsonResult = JsonConvert.SerializeObject(groupsCollection);
}
catch (Exception error)
{
errors = error.Message;
}
outErrors = errors;
return jsonResult;
}
Я вывесил бы результат, но его слишком большим. Ниже приведена сокращенная версия:
var jsonResult = [{
title: 'Products and Services',
order: 0,
items: [{
text: 'Money Transfer',
order: 11,
questionsAndAnswers: [{
question: 'Money transfer question 1',
answer: 'Money transfer answer 1',
order: 0
},
{ ... plus all items in all topics instead of just the ones in the 'Money Transfer' topic. }
]
},
{ ... plus all topics in all groups, instead of just the ones in the 'Products and services' topic. }]
}];
Заранее благодарим за любую помощь, которую может предоставить любой человек. Я открыт для более легкого решения, если оно есть.