Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional update strings in collection with LINQ

Tags:

c#

.net

linq

I want to update all strings in a List, that do not start with "http://" to start with "http://"

In a foreach I would do something like this:

url = url.StartsWith("http://") ? url : url.Insert(0, "http://");

like image 702
Gerald Hughes Avatar asked Nov 20 '25 08:11

Gerald Hughes


2 Answers

Just use a regular for loop - that's the simplest way of modifying the collection:

for (int i = 0; i < list.Count; i++)
{
    string url = list[i];
    if (!url.StartsWith("http://"))
    {
        list[i] = "http://" + url;
    }
}

If you're happy to create a new collection, it's simple:

var modifiedList = list.Select(url => url.StartsWith("http://") ? url : "http://" + url)
                       .ToList();
like image 193
Jon Skeet Avatar answered Nov 22 '25 22:11

Jon Skeet


yourlist.Where(_ => !_.StartsWith("http://")).ToList().ForEach(_ => _.Insert(0, "http://"));
like image 44
NormTheThird Avatar answered Nov 22 '25 20:11

NormTheThird