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?
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]);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With