替换列表中每个字符串的空格

时间:2012-10-12 20:16:32

标签: c#

我正在尝试使用下划线重命名每个文件的空白区域:

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

但它不起作用,我试图使用foreach循环并且它抱怨“无法分配给'元素',因为它是'foreach迭代变量'”

我该如何处理?

3 个答案:

答案 0 :(得分:4)

ConvertAll会返回新的List

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

答案 1 :(得分:2)

您可以使用以下代码块之一:

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

或:

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

或:

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

或(坏主意):

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

编辑1:  但我建议使用select函数,最好不要调用像IQueryable这样的延迟对象的.ToList()方法。

答案 2 :(得分:0)

您实际上需要重置变量files。更改最后一行,使用files的输出重置ConvertAll变量。

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