Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get absolute values of all elements in a list?

Tags:

c#

lambda

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?

Edit:

Is it possible to do this in place and not creating another list and not using a for loop?

like image 646
SamFisher83 Avatar asked Nov 10 '12 20:11

SamFisher83


2 Answers

You can use 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

for(int i = 0; i < total.Count; i++)
{
     total[i] = Math.Abs(total[i]);
}
like image 196
JKor Avatar answered Nov 15 '22 21:11

JKor


If I understand correcly you want list of abs values. Try something like

 List<long> a = new List<long>() { 10, -30, 40 }; //original list
 List<long> b = a.ConvertAll<long>(x => Math.Abs(x)); //abs list
like image 31
Igor Avatar answered Nov 15 '22 22:11

Igor