将所有数字转换为整数列表中的正数

sjo*_*ten 0 .net c# linq

如果我有一个正整数和负整数的列表:

var values = new List<int> { -30, -20, -10, 0, 10, 20, 30 };
Run Code Online (Sandbox Code Playgroud)

如何将所有值转换为正数?

var values = new List<int> { 30, 20, 10, 0, 10, 20, 30 };
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用,intValue = intValue * -1但这只能将负片转换为正片,反之亦然.此外,如果可能的话,我想使用LINQ来做到这一点.

Dav*_*idG 12

用途Math.Abs:

var positives = values.Select(i => Math.Abs(i)).ToList();
Run Code Online (Sandbox Code Playgroud)

或者使用方法组语法的缩写形式(如评论中@CommuSoft所述):

var positives = values.Select(Math.Abs).ToList();
Run Code Online (Sandbox Code Playgroud)


M.k*_*ary 5

values.Select(Math.Abs).ToList();
Run Code Online (Sandbox Code Playgroud)

要么

values.Select(n => n < 0 ? -n : n).ToList();
Run Code Online (Sandbox Code Playgroud)

或者(最快的方式)

values.Select(n => n & int.MaxValue).ToList();
Run Code Online (Sandbox Code Playgroud)