c# string.replace in foreach loop

后端 未结 5 1723
长发绾君心
长发绾君心 2021-02-07 14:01

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\"         


        
5条回答
  •  遇见更好的自我
    2021-02-07 14:59

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

提交回复
热议问题