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

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

listOfStrings.Add("13");
listOfStrings.Add("14");
listOfStrings.Add("FooBar");
listOfStrings.Add("Dummy14Item");
listOfStrings.Add("Brontosaurus165LT");

//... 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

C#
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.

Brian
Posted
Updated 12-Sep-11 8:13am
v2
Comments
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

C#
int i = 0;

listOfStrings.ForEach(x =>
{
       if (x.EndsWith("LT")) 
       {
            listOfStrings[i] = x.Replace("LT", string.Empty);
       }
   i++;
}
);
 
Share this answer
 
Comments
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