【问题标题】:Convert List to List<Dictionary> efficiently without foreach in c# [duplicate]在 c# 中不使用 foreach 有效地将 List 转换为 List<Dictionary> [重复]
【发布时间】:2019-07-10 04:47:32
【问题描述】:

假设我有一个班级列表

public class Person 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

现在我需要将字典列表转换为
假设它为List&lt;Dictionary&lt;key, value&gt;&gt;PersonDict,下面是相同的每个索引的结构。键名应动态填充为 Person 类中的属性名称。

key : "Id", Value : Person.Id
key : "Name", Value : Person.Name
key : "Age", Value : Person.Age

谁能帮忙,我已经尝试过“for each”和“Parallel For each”循环,但它需要很多时间,我有 300 万条记录要转换并且需要几个小时。

【问题讨论】:

  • 您可能需要查看Reflection
  • How to convert class into Dictionary<string,string>? 的可能重复项。只需使用Dictionary&lt;string, object&gt; 而不是Dictionary&lt;string, string&gt;
  • List&lt;Dictionary&lt;key, value&gt;&gt;PersonDict这不是一个有效的类型请具体说明,这是一个编码站点
  • 你的问题不是很清楚,但是列表中有ToDictionary方法。
  • @CodingYoshi , ToDictionaty() 方法允许为集合的每个项目创建键值对。但是 OP 想要获取字典列表,其中包含原始集合项的所有属性的键值对。

标签: c# asp.net performance


【解决方案1】:

这是一个有效的实现:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Create some sample records
        var persons = new List<Person>(){
            new Person(){Id = 1, Name = "Bob", Age = 30},
            new Person(){Id = 2, Name = "Jane", Age = 31},
            new Person(){Id = 3, Name = "Mary", Age = 32}
        };

        // Use Reflection to retrieve public properties
        var properties = typeof(Person).GetProperties();

        // Create a list to store the dictionaries      
        var listOfDictionary = new List<Dictionary<string, string>>();

        // For each person class
        foreach(var person in persons){
            // Create a new dictionary
            var dict = new Dictionary<string,string>();
            // For each property
            foreach(var prop in properties){
                // Add the name and value of the property to the dictionary
                dict.Add(prop.Name, prop.GetValue(person).ToString());

            }
            // Add new dictionary to our list
            listOfDictionary.Add(dict);

        }


        // Check the contents of our list
        foreach(var dict in listOfDictionary){      
            Console.WriteLine(string.Join(",", dict.Keys));
            Console.WriteLine(string.Join(",", dict.Values));
        }

    }

    public class Person 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

您提到您有数百万条记录要转换。创建数百万个Dictionary&lt;&gt; 实例可能不是最好的主意,也不将它们全部保存在内存中。但是,如果不知道您的最终目标是什么,就很难推荐一些东西。

【讨论】:

  • 字典值可以使用object类型来存储原始属性值。
  • @Alexander 是的,这是真的,但是这也会产生拳击开销
  • @MichaelRandall - 你有没有遇到过拳击开销很大的情况?
  • @Enigmativity 如果 op 想要保存每个 cpu 周期,op 会
  • @MichaelRandall - 是的,那么您可以建议他们用机器语言编写代码。但既然他们使用的是 C#,那么极端的性能可能不是他们最大的目标。
【解决方案2】:

这与此处的其他答案几乎相同,但使用了更简洁的语法。只是偏好问题。

List<Person> persons = new List<Person> {
    new Person { Id = 1, Name = "Sally", Age = 10 },
    new Person { Id = 2, Name = "Bob", Age = 9 },
};

List<Dictionary<string, string>> listOfDictionaries =
    persons
        .Select(p => new Dictionary<string, string>
        {
            ["Id"] = p.Id.ToString(),
            ["Name"] = p.Name,
            ["Age"] = p.Age.ToString(),
        })
        .ToList();

【讨论】:

  • 希望您不要介意编辑。我最喜欢你的回答,但它的布局方式让我很难阅读,我觉得它失去了知名度,因此失去了投票。
  • 我还建议您包含源数据,以表明您可以实际运行您的代码并产生正确的结果。
  • 你确定字典构造函数使用正确吗?
  • @Alexander - 是的,我运行并测试了这段代码。它使用了另一种语法。这是合法的。
  • @Alexander 字典初始化语法 was introduced in C# 6.0,随 Visual Studio 2015 一起发布。它确实需要足够现代的工具集,但它可以工作。
猜你喜欢
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
相关资源
最近更新 更多