Reputation: 195
I have a List<int> myInts
and want to multiply all with 10. I want to use linq (not foreach loop).I tryed this but nothing happend:
List<int> myInts = new List<int>() { 1, 2, 3 };
myInts .ForEach(act => act=act*10);
Of what do I have to take care in the .ForEach(...)
part? And yes, I want to use ForEach if it is somehow possible.
Probably its simple, but I cant see it, I apoligize. Thank you all!
Upvotes: 0
Views: 2387
Reputation: 195
To use a .Select
or .ConvertAll
are good solutions.
But my intention was to let "ForEach
" return an alterd list.
I found out, over msdn documentation, that this isn´t possible because ForEach is a void
type and has no returntype.
This kind of action works if I would have objects in my List instead of ints. Then I would be able to use the "void" Method to change the properties of my objects.
Upvotes: 1
Reputation: 61865
"Nothing happens" because reassigning to the local variable (act
) has no effect in the caller (ForEach
) - C# is Call By Value (except for ref/out parameters).
To modify the list in place, simply use a standard for-each over the indices (which I find readable and upfront of the side-effect intent):
var myInts = new List<int>() { 1, 2, 3 };
for (var i = 0; i < myInts.Count; i++) {
myInts[i] = myInts[i] * 10;
}
To perform the operation and create a new list/sequence (which can be re-assigned to the same variable), see IEnumerable.Select
which is a map transformation.
Upvotes: 3
Reputation: 4892
Another and simpler solution:
list = list.ConvertAll(i => i * 10);
Upvotes: 3
Reputation: 4892
try this:
Enumerable.Range(0, myInts.Count).ToList().ForEach(i => myInts[i] = myInts[i] * 10);
Upvotes: 0
Reputation: 107237
What is happening is that you are getting a value copy of the int to your the lambda, which so you won't be able to change the 'external' int.
How about projecting a new list?
List<int> myInts = new List<int>() { 1, 2, 3 };
myInts = myInts.Select(act => act*10).ToList();
Upvotes: 1
Reputation: 6105
Do you mean like this ?
List<int> _tempList = new List<int>();
myInts.ToList().ForEach(x => _tempList.Add(x * 10));
Upvotes: 0
Reputation: 5380
From MSDN documentation:
Modifying the underlying collection in the body of the Action<T> delegate
is not supported and causes undefined behavior.
So, you need to project your exisistin List into a new one, or you need to use a for loop if you must modify the List "in place"
Regards
Upvotes: 2
Reputation: 623
This creates a new instance of List.
myInts = myInts.Select(p=>p*10).ToList();
Upvotes: 5