如何将列表中的每个元素除以整数? C#

时间:2013-12-14 13:57:10

标签: c# list

所以我创建了一个包含双精度数的列表,是否可以用整数变量划分此列表中的每个元素?

List<Double> amount = new List<Double>();

4 个答案:

答案 0 :(得分:7)

只需使用修改后的内容创建一个新列表:

var newAmounts = amount.Select(x => x / 10).ToList();

创建新数据比修改现有数据更不容易出错。

答案 1 :(得分:5)


的foreach

您可以使用foreach迭代每个项目:

foreach(var item in amount)
{
    var result = item / 3;
}

如果要将结果存储在新列表中,可以在循环内执行...

var newList = new List<double>(amount.Count); //<-- set capacity for performance
foreach(var item in amount)
{
    newList.Add(item / 3);
}

LINQ

...或将Linq用于IEnumerable<double>

var newList = from item in amount select item / 3;

您也可以使用Linq扩展方法:

var newList = amount.Select(item => item / 3);

或者,如果您想要Linq的List<double>,可以使用ToList()执行此操作:

var newList = (from item in amount select item / 3).ToList();

......或......

var newList = amount.Select(item => item / 3).ToList();

作为替代方案,您可以使用简单的for

for (int index = 0; index < amount.Count; index++)
{
    var result = amount[index] / 3;
}

这种方法可以让您进行适当的修改:

for (int index = 0; index < amount.Count; index++)
{
    amount[index] = amount[index] / 3;
}

PLINQ

您也可以考虑使用Parallel LINQ(AsParallel):

var newList = amount.AsParallel().Select(item => item / 3).ToList();

警告:结果可能无序。

这将利用多核CPU,通过并行运行每个项目的操作。这对于大型列表以及对每个项目独立的操作尤其有用。


比较

  1. foreach:易于阅读和书写,易于记忆。还允许进行一些优化。
  2. Linq:如果你习惯使用SQL,那就更好了,也允许延迟执行。
  3. for:执行操作需要更少的内存。允许更多控制。
  4. PLinq:您对Linq的喜爱,针对多核进行了优化。虽然需要谨慎。

答案 2 :(得分:1)

当然,简单的方法是迭代列表并划分每个数字:

foreach(var d in amount) {
    var result = d / 3;
}

您可以将结果存储在新列表中。

答案 3 :(得分:1)

如果您想要修改相同的实例(而不是创建新的集合),请执行以下操作:

for (int i = 0; i < amount.Count; ++i)
    amount[i] /= yourInt32Divisor;