18

Somehow I can't seem to get string replacement within a foreach loop in C# to work. My code is as follows :

foreach (string s in names)
{
    s.Replace("pdf", "txt");
}

Am still quite new to LINQ so pardon me if this sounds amateurish ;)

5 Answers 5

38

You say you're after a LINQ solution... that's easy:

var replacedNames = names.Select(x => x.Replace("pdf", "txt"));

We don't know the type of names, but if you want to assign back to it you could potentially use ToArray or ToList:

// If names is a List<T>
names = names.Select(x => x.Replace("pdf", "txt")).ToList();
// If names is an array
names = names.Select(x => x.Replace("pdf", "txt")).ToArray();

You should be aware that the code that you've posted isn't using LINQ at all at the moment though...

Sign up to request clarification or add additional context in comments.

Comments

27

Strings in C# are immutable (does not change), so s.Replace will return a new string. Unfortunately this means you cannot use foreach to do the update. If names is an array this should work:

for(int i = 0; i < names.Length; i++)
{
    names[i] = names[i].Replace("pdf", "txt");
}

1 Comment

It will work for a List<string> too. Just replace Length with Count
4

As others have mentioned you'd need to use a for loop to do this in-place. However, if you don't need the operation to be done in-place (i.e. the results can be a different collection), then you could also do it as a linq query, e.g.

var results = from name in names select name.Replace("pdf", "txt");

One thing though - it looks like you are trying to change the extension of some file names. If that's what you are trying to do then I'd recommend Path.ChangeExtension which is specifically designed for this purpose.

var results = from name in names select Path.ChangeExtension(name, "txt");

4 Comments

Using a query expression here seems overkill - if you're just doing a single Select, why not call it directly? +1 for Path.ChangeExtension though.
@Jon - I just think that query expressions look nicer and are a little easier to read. It all compiles down to the same code, and typing a few extra characters doesn't really bother me. If I was doing something that can't be expressed in a query such as using skip/take or converting to a list then I'd probably use the extension methods directly.
I guess it's just personal preference... I certainly love query expressions when they get more complicated, but if you're just doing a single filter or a single projection, they seem a less direct way of expressing that.
@Jon - Another reason for me is that often simple queries can turn into more complex ones, e.g. in the above code I might need to add where Path.GetExtension(name) == ".pdf" to make the code using the Path class match the intent of the original. Writing it as a query in the first place means it doesn't have to be changed too much if it gets more complex in the future. But to be honest I don't care that much either way, and it probably depends more on what mood I'm in or how the other queries in the method are written as much as anything!
0

s.Replace is a function so you would like s=s.Replace().. although it's better to use StringBuilder. (see upper answer)

1 Comment

Why would using a StringBuilder be better here? It's not like multiple replacements are being performed on the same string.
-3

Why use replace? It will make the application slow. Use regex instead:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.