【问题标题】:Quickest way to assign each value of list to a value of another list将列表的每个值分配给另一个列表的值的最快方法
【发布时间】:2018-06-19 17:11:14
【问题描述】:

如果说,我们有一个包含序列号的列表和另一个包含产品的列表,这是为每个产品分配一个序列号的最快(和更优雅)的方式?

可以使用经典:

 var serialNumbers = CreateSerialNumbers().ToList();
 var index = 0;
 foreach (var product in Products)
 {
     product.SerialNumber = serialNumbers[index];
     index++;
 }

for

for (int index= 0; index < Products.Count; index++)
{
    Products[index].SerialNumber = serialNumbers[index];
}

但是有更快/更优雅的方法吗?也许与Linq?

【问题讨论】:

  • LINQ 真的只是一系列foreach 语句,你的任何一个解决方案都可以。
  • 我认为for 循环的速度与您将获得的一样快,而且它只有 2 行。但是为什么要跳过for 版本中的最后一个产品呢?
  • 请记住,LINQ 中的Q 代表query,它的目的是读取数据,而不是更改它。
  • 这里看起来forforeach 都很好,但看看你的设计,我觉得有一种方法可以“改进”你的代码。当您使用CreateSerialNumbers() 生成一堆序列号时,我假设您正在经历某种循环。因此,如果您被允许更改方法,请传递您的Products 列表中的ref 并在创建时分配序列号。避免在列表中循环两次。只是一个想法。
  • @RafaGomez 好的,那为什么不直接创建一个方法 IEnumerable&lt;Product&gt; AssignSerialNumers(IEnumerable&lt;Product&gt; products) 呢?然后只循环遍历每个Product 并为其分配一个序列号,然后返回修改后的集合?

标签: c# performance collections


【解决方案1】:

我会这样做:

for (int index= 0; index < Products.Count; index++)
{
    Products[index].SerialNumber = serialNumbers[index];
}

...但是您需要确保serialNumbers[index] 也没有越界。也许……

for (int index= 0; index < Products.Count; index++)
{
    if(serialNumbers.Count >= index
         Products[index].SerialNumber = serialNumbers[index];
    else
         index = Products.Count;
}

这并不是最安全的做法,但在这里会起作用。

【讨论】:

  • 基于 OP 中的一些 cmets,我认为这不再是最好的方法了...
猜你喜欢
  • 2017-08-25
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2019-07-01
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多