convert dictionary to list of objects in C#

Viewed 14220

I have a dictionary:

Dictionary<string, string> valuesDict = new Dictionary<string, string> {
    {“Q1”, “A1”},
    {“Q2”, “A2”},
    {“Q3”, “A3”},
    {“Q4”, “A4”} /*20000 Q and A pairs*/
};

Inorder to load this to a third party interface which only accepts a list of objects (of class QuestionAnswer), I am manually converting it to a list like so

Public Class QuestionAnswer {
    Public string Question;
    Public string Answer;
}

objects of the QuestionAnswer class are then created within the loop

List<QuestionAnswer> qaList = new List<QuestionAnswer>();
foreach(var key in valuesDict.Keys) {
    qaList.add(new QuestionAnswer {Question = key, Answer = valuesDict[key]});
}

I want to know if there is a faster way to populate this list from the dictionary.

What I have found so far: While looking around for the solution, I came across a solution for a conversion of simple Dictionary to List of simple types like so: Convert dictionary to List<KeyValuePair> Could someone please help me in utilizing this solution to my case please. I am also open to any other solution that can remove this overhead.

4 Answers
Related