user1592916
user1592916

Reputation:

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

I have the following loop:

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

into a Linq expression?

Upvotes: 3

Views: 161

Answers (2)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

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());

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

Upvotes: 4

Related Questions