Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to transform a For loop into a Linq expression?

Tags:

c#

for-loop

linq

I have the following loop:

for (var i = 0; i < myStringList.Count; i++)
{
    myStringList[i] = myStringList[i].ToUpper();
}

into a Linq expression?


2 Answers

Use this

myStringList = myStringList.Select(x => x.ToUpper()).ToList();

I have used .ToList() in the end assuming that myStringList is a List<string>.

FoodforThought: In List there is a method ForEach() which performs an action on each item like this.

myStringList.ForEach(x => x.Foo = Bar);

But that cannot be used here as that method can be used to change a property of an item but cannot be used to change the item itself.

So this will not do anything

    myStringList.ForEach(x => x = x.ToUpper());
like image 168
Nikhil Agrawal Avatar answered Nov 26 '25 01:11

Nikhil Agrawal


myStringList = myStringList.Select(x => x.ToUpper()).ToList();
like image 44
Darin Dimitrov Avatar answered Nov 26 '25 01:11

Darin Dimitrov