SW2702
SW2702

Reputation: 199

Changing a string in a List using lambda expression

I have a list of of road names and would like it iterate through them and change where it finds "Adams Road 1a", "Adams Road 2a" ... To just "Adams Road".

The code below will just change one of them items in the list.

I would like to change all of them.

communityHouses[communityHouses.FindIndex(
ind => ind.Road.Contains("Adams Road"))].Road= "Adams Road"; 

Upvotes: 0

Views: 892

Answers (1)

Liu
Liu

Reputation: 982

you can use the List<T>.ForEach method.

communityHouses.ForEach(ch =>
{
    if (ch.Road.Contains("Adams Road")) ch.Road = "Adams Road";
});

Update:

Thanks @Flater's suggestion.

communityHouses.Where(ch => ch.Road.Contains("Adams Road"))
               .ToList().
               .ForEach(ch => ch.Road = "Adams Road");

I've also done some performance test and the first one always performs better than the second one.

Here's my test:

public class House
{
    public string Road { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<House> list1 = new List<House>();
        List<House> list2 = new List<House>();
        var sample = 50000;
        for (int i = 0; i < sample; i++)
        {
            if (i % 3 == 0)
            {
                list1.Add(new House() {Road = "Adam Road 1"});
                list2.Add(new House() {Road = "Adam Road 1"});
            }
            else
            {
                list1.Add(new House(){Road = "Random"});
                list2.Add(new House(){Road = "Random"});   
            }
        }
    
        Console.WriteLine("Test " + sample + " samples:");
        Stopwatch sw = new Stopwatch();
        sw.Start();
        list1.ForEach(l =>
        {
            if (l.Road.Contains("Adam Road")) l.Road = "Adams Road";
        });
        sw.Stop();
        Console.WriteLine("1 - ForEach: " + sw.ElapsedMilliseconds + " ms");
        
        sw.Reset();
        sw.Start();
        list2.Where(l=> l.Road.Contains("Adam Road")).ToList().ForEach(l =>
        
            l.Road = "Adams Road"
        );
        sw.Stop();
        Console.WriteLine("2 - Where.ToList.ForEach: " + sw.ElapsedMilliseconds + " ms");
    }
}

Test Result:

Test 50000 samples:

1 - ForEach: 2 ms

2 - Where.ToList.ForEach: 3 ms

Test 500000 samples:

1 - ForEach: 18 ms

2 - Where.ToList.ForEach: 21 ms

Test 5000000 samples:

1 - ForEach: 179 ms

2 - Where.ToList.ForEach: 221 ms

Update:

I did another test where I changed the i % 3 to i % 10000 and now the second one performed better.

I would say it's really doesn't matter which one to use. Just choose the one you feel more clean and understandable. I will go for the second.

Upvotes: 3

Related Questions