Adrien Neveu
Adrien Neveu

Reputation: 827

Apply a predicate on all elements of a list using LINQ

I want to update a list by applying a predicate function on every elements.

Here's how I would do it without using LINQ:

for(int i = 0; i < filesToCheck.Count; i++)
{
    while (filesToCheck[i][0] == '/' || filesToCheck[i][0] == '\\')
        filesToCheck[i] = filesToCheck[i].Substring(1);   
}

How can I do that with LINQ?

Upvotes: 4

Views: 1814

Answers (1)

Igal Tabachnik
Igal Tabachnik

Reputation: 31548

If all you need is to remove some characters from start of every fileName, you can use TrimStart for that, and then:

var list = filesToCheck.Select(f => f.TrimStart('/', '\\'));

EDIT: you could do this without LINQ, of course, but the main issue here is your while loop, rather than the use of for: it took me a few seconds to mentally parse the while loop to figure out what it does. This does not convey intent, I have to mentally execute it to understand it. Alternatively, you could rewrite it like this:

for (int i = 0; i < filesToCheck.Count; i++)
{
    filesToCheck[i] = GetValueWithoutSlashes(filesToCheck[i]);
}

then it would be clear to everyone reading this, and also allowing you to change implementation of GetValueWithoutSlashes to be whatever you want, e.g.

private string GetValueWithoutSlashes(string value)
{ 
    return value.TrimStart('/', '\\');
}

Upvotes: 6

Related Questions