convert dictionary to list of objects in C#
Solution 1
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.
Solution 2
You can create a list with LINQ by projecting each KeyValuePair
of the dictionary into your QuestionAnswer
object:
var qaList =
valuesDict.Select(kvp => new QuestionAnswer { Question = kvp.Key, Answer = kvp.Value })
.ToList()
Ganesh Kamath - 'Code Frenzy'
Love to Code & play basketball. Work at AMD on Client Manageability Solutions - DASH-DMTF
Updated on June 09, 2022Comments
-
Ganesh Kamath - 'Code Frenzy' almost 2 years
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.