[英]Using C# 4.8: Most efficient way to remove items matching string patterns from a string array or string list
I need to remove items from the list that match a collection of string patterns.我需要从列表中删除与字符串模式集合匹配的项目。 If needed, I can loop through the list/array of patterns to remove rather than matching all of them at once.
如果需要,我可以遍历模式列表/数组来删除而不是一次匹配所有模式。
Note: the string patterns are dynamic and we don't know what will be passed in.注意:字符串模式是动态的,我们不知道会传入什么。
We do know the patterns can have Asterisk and/or Question Marks, and have the same function as in:我们确实知道模式可以有星号和/或问号,并且具有与以下相同的 function:
System.IO.Directory.GetFiles(, ); System.IO.Directory.GetFiles(, );
Where ?xyz.txt
would find 1xyz.txt
, 2xyz.txt
, but not 12xyz.txt
and not xyz.txt
哪里
?xyz.txt
会找到1xyz.txt
, 2xyz.txt
,但不是12xyz.txt
而不是xyz.txt
This is what I came up with which does not work.这是我想出的,但不起作用。
string exclude = "*yf*";
List<string> listRemaining = listAll.Where(x => !listAll.Contains(exclude)).ToList();
This is an example of patterns for items to remove from the list:这是从列表中删除项目的模式示例:
*yf*
*xName.txt
?MyFileName*
And this is a sample list of strings where we need to remove items matching the 3 patterns above:这是一个示例字符串列表,我们需要在其中删除与上述 3 种模式匹配的项目:
AyFileName.log
AyFilexName.txt
ByFilexName.log
ByFileName.txt
zMyFileName.log
zMyFileName.txt
SomeFancyFileName.log
SomeFancyFileName.txt
TodayFileName.log
TodayFileName.txt
UglyFileName.log
UglyFileName.txt
Items to be removed?要删除的项目?
Pattern to remove: *yf*
要删除的模式:
*yf*
will remove:将删除:
`SomeFancyFileName.log`
`SomeFancyFileName.txt`
`UglyFileName.log`
`UglyFileName.txt`
Pattern to remove: *xName.txt
要删除的模式:
*xName.txt
will remove: AyFilexName.txt
将删除:
AyFilexName.txt
Pattern to remove: ?MyFileName*
要删除的模式:
?MyFileName*
will remove: zMyFileName.log
zMyFileName.txt
将删除:
zMyFileName.log
zMyFileName.txt
Thank you.谢谢你。
The best solution would be the File globbing as @jwdonahue mentioned.最好的解决方案是@jwdonahue 提到的 File globbing。
https://learn.microsoft.com/en-us/do.net/core/extensions/file-globbing https://learn.microsoft.com/en-us/do.net/core/extensions/file-globbing
But if you want to build your own solution for that, this might be a start.但如果您想为此构建自己的解决方案,这可能是一个开始。
public static IEnumerable<string> Filter(string pattern, IEnumerable<string> list) {
return list.Where(e =>!Match(pattern, e));
}
public static bool Match(string pattern, string input) {
var modifiedPattern = pattern
.Replace(@"\", @"\\")
.Replace(".", @"\.")
.Replace("*", ".*")
.Replace("?", ".");
modifiedPattern = "^" + modifiedPattern + "$";
return Regex.IsMatch(input, modifiedPattern, RegexOptions.IgnoreCase);
}
Which you can call like你可以这样称呼
var filterPattern = "?MyFileName*";
var listRemaining = Filter(filterPattern, listAll).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.