C# 如何获取列表中所有元素的绝对值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13325838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get absolute values of all elements in a list?
提问by SamFisher83
I want to do something like below:
我想做如下事情:
total.ForEach(x => x = Math.Abs(x));
However x is not a reference value. How would I go about doing it?
但是 x 不是参考值。我将如何去做?
Edit:
编辑:
Is it possible to do this in place and not creating another list and not using a for loop?
是否可以就地执行此操作而不创建另一个列表而不使用 for 循环?
采纳答案by JKor
You can use Linq.
您可以使用 Linq。
total.Select(x => Math.Abs(x)).ToList();
That will give you a new list of the absolute values in total.
If you want to modify in place
这会给你一个新的绝对值列表total。如果你想就地修改
for(int i = 0; i < total.Count; i++)
{
total[i] = Math.Abs(total[i]);
}
回答by Igor
If I understand correcly you want list of abs values. Try something like
如果我理解正确,您需要 abs 值列表。尝试类似的东西
List<long> a = new List<long>() { 10, -30, 40 }; //original list
List<long> b = a.ConvertAll<long>(x => Math.Abs(x)); //abs list
回答by Toby Simmerling
This will be slightly more efficient as uses less method calls.
由于使用较少的方法调用,这将稍微更有效。
total.Select(x => x * -1).ToList();

