简体   繁体   English

将字典转换为C#中的对象列表

[英]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 为了将其加载到仅接受对象列表(类QuestionAnswer)的第三方接口,我手动将其转换为如此列表

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

objects of the QuestionAnswer class are then created within the loop 然后在循环内创建QuestionAnswer类的对象

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. 到目前为止我发现了什么:在寻找解决方案时,我遇到了一个简单的Dictionary转换为简单类型列表的解决方案,如下所示: 将字典转换为List <KeyValuePair>有人可以帮我利用这个解决方案我的情况请。 I am also open to any other solution that can remove this overhead. 我也对任何可以消除这种开销的其他解决方案持开放态度。

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. 您可以使用基于LinQ的解决方案,但这样做速度较慢 ,您需要最佳解决方案。

You can create a list with LINQ by projecting each KeyValuePair of the dictionary into your QuestionAnswer object: 您可以通过将字典的每个KeyValuePair投影到QuestionAnswer对象中来创建包含LINQ的列表:

 var qaList = 
    valuesDict.Select(kvp => new QuestionAnswer { Question = kvp.Key, Answer = kvp.Value })
              .ToList()

Faster? 快点? Well, yes, absolutely, iterate directly the dictionary, not the Keys collection: 嗯,是的,绝对,直接迭代字典,而不是Keys集合:

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

Or better yet, using System.Linq : 或者更好的是,使用System.Linq

valuesDict.Select(kv => new QuestionAnswer(kv.Key, kv.Value);

In your code you are performing an unecessary key search on each iteration. 在您的代码中,您在每次迭代时执行不必要的密钥搜索。

Basically ther are two common approaches. 基本上是两种常见的方法。 Using a foreach or LINQ. 使用foreach或LINQ。 To check the performance you can use a stopwatch and run a simple code like this: 要检查性能,您可以使用秒表并运行如下的简单代码:

Dictionary<string, string> valuesDict = new Dictionary<string, string>();
for (uint i = 0; i < 60000; i++)
{
    valuesDict.Add(i.ToString(), i.ToString());
}

List<QuestionAnswer> qaList;
Stopwatch stp = new Stopwatch();

stp.Start();
//LINQ approach
qaList = valuesDict.Select(kv => new QuestionAnswer { Question = kv.Key, Answer = kv.Value }).ToList();
stp.Stop();
Console.WriteLine(stp.ElapsedTicks);

stp.Restart();
//Foreach approach
qaList = new List<QuestionAnswer>();
foreach (var item in valuesDict)
{
    qaList.Add(new QuestionAnswer { Question = item.Key, Answer = item.Value });
}
stp.Stop();
Console.WriteLine(stp.ElapsedTicks);

My result: Foreach performes about 30% faster than the LINQ approach. 我的结果: Foreach执行速度比LINQ方法快30%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM