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

I want to do something like below:

total.ForEach(x => x = Math.Abs(x)); 

However, x is not a reference value. How can I do it?

Edit:

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

+4
source share
2 answers

You can use Linq.

 total.Select(x => Math.Abs(x)).ToList(); 

This will give you a new list of absolute values ​​in total . If you want to change in place

 for(int i = 0; i < total.Count; i++) { total[i] = Math.Abs(total[i]); } 
+13
source

If I understand correctly, you need a 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 
+4
source

Source: https://habr.com/ru/post/1445250/


All Articles