Reputation: 2095
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
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