【问题标题】:List of Array of string to Array of Each element of Array字符串数组列表到数组每个元素的数组
【发布时间】:2020-04-08 10:47:34
【问题描述】:

所以我有一个字符串数组列表,如下所示:

        List<string[]> ArrayList = new List<string[]>();
        ArrayList.Add(new string[] { "7112432","Gagan","Human Resource"});
        ArrayList.Add(new string[] { "7112433", "Mukesh", "Information Technology" });
        ArrayList.Add(new string[] { "7112434", "Steve", "Human Resource" });
        ArrayList.Add(new string[] { "7112435", "Trish", "Human Resource" });

我希望他们将它们转换为单独的数组,例如:

        EmployeeNumber=["7112432","7112433","7112434","7112435"]
        Name =["Gagan", "Mukesh", "Steve", "Trish"]
        Department =["Human Resource", "Information Technology", "Human Resource", "Human Resource"]

我已经通过使用 foreach 循环遍历列表来实现它,但我想知道是否有任何有效的方法可以做到这一点,因为我在原始 List 中有 2000 万个项目

【问题讨论】:

  • 为了提高效率,您应该在填充原始列表的地方执行此操作
  • 您可以使用 linq 转置数组列表,但我怀疑它的性能会更好。见stackoverflow.com/questions/39484996/…。正如@OguzOzgul 所说,最好的选择是创建具有所需结构的数据。
  • 显示您的 foreach 循环,以便我们提出改进建议。另外你通常不希望在内存中加载这么大的列表,所以我建议你考虑如何逐个处理数据。
  • 当最终目标是得到 3 +20.000.000 长的重复信息数组时询问效率是相当讽刺的......这看起来像XY problem。为什么需要这 3 个数组?您在这里的目标是什么?

标签: c# arrays generic-list


【解决方案1】:

这个解决方案启发了我:Rotate - Transposing a List<List<string>> using LINQ C#

这里是您可以根据需要使用的代码:


        List<string[]> ArrayList = new List<string[]>();
        for (int i = 0; i < 20000000; i++)
        {
            //The simulation of the 20.000.000 arrays of the list takes some time (+- 10s)...
            //But you already have the list so you can skip this part of the code
            ArrayList.Add(new string[] { i.ToString(), "Gagan", "Human Resource", "AAA" });
        }

        var millis = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();

        List<List<string>> results = ArrayList.SelectMany
        (theArray => theArray.Select((itemInArray, indexInArray) => new { itemInArray, indexInArray })) //All single elements
        .GroupBy(i => i.indexInArray, i => i.itemInArray) //Group them
        .Select(g => g.ToList())
        .ToList();

        var seconds = (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - millis) / 1000d; //9.8 s

【讨论】:

  • 是的,我有。这需要 9.8 秒,但如果将其与 foreach 循环进行比较,这不算什么。尽管如此,您可以将其放在线程或异步任务中。所以我认为这是一个很好的解决方案
猜你喜欢
  • 2013-10-22
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多