Click here to Skip to main content
15,789,463 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I want to do the following:

List<string> listOfStrings = new List<string>();


//... add items here ...

// iterate through the list and find all items
// ending with "LT" and remove the last two characters
// from those items, but leave the list intact
for (int i = 0; i < listOfStrings.Count; i++)
    if (listOfStrings[i].EndsWith("LT"))
        listOfStrings[i] = listOfStrings[i].Replace("LT", "");

// list should now be
// 13
// 14
// FooBar
// Dummy14Item
// Brontosaurus165
// can I make this change with LINQ?

So is there a way to make a projection of the List<t> that contains essentially the same items except for the modification? I tried

listOfStrings.ForEach(x => { if (x.EndsWith("LT")) x = x.Replace("LT", ""); });

But, unless I am doing something incorrectly, it doesn't seem to be working. One reason may be because the ForEach function takes as its parameter an Action<T> delegate, which passes T obj by value, not by reference.

Does anyone have a hint? I just hate the first block with the for(int i;i < list.Count; i++ ), it seems so gradeschool.

Updated 12-Sep-11 9:13am
Herman<T>.Instance 12-Sep-11 15:35pm    
in stead of the for loop you could have used foreach (string value in listOfString) {if value.EndsWith("LT") ......

1 solution

int i = 0;

listOfStrings.ForEach(x =>
       if (x.EndsWith("LT")) 
            listOfStrings[i] = x.Replace("LT", string.Empty);
Share this answer
Brian C Hart 12-Sep-11 16:45pm    
I would also do

list = list.ConvertAll<string>(x => x.EndsWith("LT") ? x.Replace("LT", "") : x);

however this is another process of O(n) complexity that replaces my list with a whole new list, identical to the old except for the changed items. digimanus's answer is close; i just was hoping that i wouldn't have to declare an int i outside the ForEach call. It's almost as gradeschool as the OP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900