sjokkogutten
sjokkogutten

Reputation: 2095

Convert all numbers to positives in a List of integers

If I have a list of both positive and negative integers:

var values = new List<int> { -30, -20, -10, 0, 10, 20, 30 };

How do I convert all the values to positive numbers?

var values = new List<int> { 30, 20, 10, 0, 10, 20, 30 };

I know I could use intValue = intValue * -1 but that would only convert the negatives to positives and vice versa. Besides, if possible I would like to do this using LINQ.

Upvotes: 1

Views: 1966

Answers (2)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

values.Select(Math.Abs).ToList();

Or

values.Select(n => n < 0 ? -n : n).ToList();

Or (fastest way)

values.Select(n => n & int.MaxValue).ToList();

Upvotes: 5

DavidG
DavidG

Reputation: 119017

Use Math.Abs:

var positives = values.Select(i => Math.Abs(i)).ToList();

Or the shortened form using method group syntax (as mentioned by @CommuSoft in the comments):

var positives = values.Select(Math.Abs).ToList();

Upvotes: 13

Related Questions