如何从 C# 列表中的条目中删除数组中给定的子字符串
How to delete substrings given in an array from entries in a list in c#
我有一个字符串数组要删除:
string[] delStrings = {"aaa", "bbb", "ccc", "ddd"}
然后我有一个目录列表:
List<string> dirs = new(Directory.EnumerateDirectories(path));
到目前为止我有:
var matches = from dir in dirs
where delStrings.Any( str => dir.Contains(str) )
select dir;
foreach ( string oldName in matches ) {
// ==> how to delete any delString <==
// something such
// string subString = delStrings.Any( str => oldName.Contains(str) )
string newName = oldName.Replace( subString, string.Empty );
System.IO.Directory.Move( oldName, newName );
}
其中获取所有包含 delString 的目录名称。
现在我想将 dirs 的每个条目中的任何 delString 替换为
string.Empty.
如何做到最有效?
不做火柴。而是做两个循环:
foreach (var dir in dirs)
{
foreach (var match in delStrings.ToList())
{
if (match == dir)
{
dir = string.empty;
break;
}
}
}
我会按照你的要求这样做:
foreach (string oldName in Directory.EnumerateDirectories(path).ToList())
{
string newName = delStrings.Aggregate(oldName, (a, x) => a.Replace(x, String.Empty));
if (newName != oldName)
{
System.IO.Directory.Move(oldName, newName);
}
}
这只是尝试一次替换 oldName
中的每个 delStrings
。如果该字符串不存在,则不要更改旧字符串。
我有一个字符串数组要删除:
string[] delStrings = {"aaa", "bbb", "ccc", "ddd"}
然后我有一个目录列表:
List<string> dirs = new(Directory.EnumerateDirectories(path));
到目前为止我有:
var matches = from dir in dirs
where delStrings.Any( str => dir.Contains(str) )
select dir;
foreach ( string oldName in matches ) {
// ==> how to delete any delString <==
// something such
// string subString = delStrings.Any( str => oldName.Contains(str) )
string newName = oldName.Replace( subString, string.Empty );
System.IO.Directory.Move( oldName, newName );
}
其中获取所有包含 delString 的目录名称。 现在我想将 dirs 的每个条目中的任何 delString 替换为 string.Empty.
如何做到最有效?
不做火柴。而是做两个循环:
foreach (var dir in dirs)
{
foreach (var match in delStrings.ToList())
{
if (match == dir)
{
dir = string.empty;
break;
}
}
}
我会按照你的要求这样做:
foreach (string oldName in Directory.EnumerateDirectories(path).ToList())
{
string newName = delStrings.Aggregate(oldName, (a, x) => a.Replace(x, String.Empty));
if (newName != oldName)
{
System.IO.Directory.Move(oldName, newName);
}
}
这只是尝试一次替换 oldName
中的每个 delStrings
。如果该字符串不存在,则不要更改旧字符串。