简体   繁体   中英

replace space for every string in the list

I am trying to renaming every file's empty space with an underscore:

DirectoryInfo dir = new DirectoryInfo(@"Q:\Audio");
var files = (from f in dir.GetFiles() select f.FullName);
files.ToList().ConvertAll( s => s.Replace( " ", "_") );

But it's not working, I tried to use a foreach loop and it complains "Cannot assign to 'element' because it is a 'foreach iteration variable'"

How do I approach this?

ConvertAll返回一个新的List

var renamedFiles = files.ToList().ConvertAll(s => s.Replace(" ", "_"));

You can use one of code blocks below:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName.Replace(" ", "_"));

or:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = (from fn in files select fn.Replace(" ", "_"));

or:

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = files.Select(s => s.Replace(" ", "_"));

or (Bad Idea):

DirectoryInfo dir = new DirectoryInfo(@"C:\");
var files = (from f in dir.GetFiles() select f.FullName);
var fileNames = files.ToList().ConvertAll(s => s.Replace(" ", "_"));

EDIT 1: but i suggest to use select function, its better to not call .ToList() method for deferred objects like IQueryable.

you actually need to reset your variable files . Change you last line to reset the files variable with the output from ConvertAll .

files = files.ToList().ConvertAll( s => s.Replace( " ", "_") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM