Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert dictionary to list of objects in C#

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.

like image 982
Ganesh Kamath - 'Code Frenzy' Avatar asked Dec 05 '22 14:12

Ganesh Kamath - 'Code Frenzy'


1 Answers

You're doing an unnecessary lookup for the key:

foreach(var item in valuesDict) {
    qaList.add(new QuestionAnswer {Question = item.Key, Answer = item.Value});
}

You can also provide the list count when intializing to avoid resize:

List<QuestionAnswer> qaList = new List<QuestionAnswer>(valuesDict.Keys.Count);

You can use LinQ-based solutions, but that is slower and you're asking for optimal solution.

like image 73
Zein Makki Avatar answered Feb 21 '23 15:02

Zein Makki