Soooo ......我正在编写一个工具,其任务是根据参数在服务器上收集xmls。
这是我到目前为止的代码:
private List<string> GetListXmls(string strPath, List<string> colctNames)
{
string regexExpr = "\\\\\\\\" + strStager + "\\\\APPLI\\\\" + strEnvir + "\\\\[a-zA-Z]{3}\\\\Bin\\\\";
if(colctNames == null)
{
List<string> xmlColct = Directory.GetFiles(strPath, "*.*", SearchOption.AllDirectories)
.Where(x => Regex.IsMatch(x, regexExpr, RegexOptions.IgnoreCase) &&
x.ToLower().Contains("msgtrait") &&
x.EndsWith(".xml"))
.ToList();
return xmlColct;
}
else
{
List<string> xmlColct = Directory.GetFiles(strPath, "*.*", SearchOption.AllDirectories)
.Where(x => Regex.IsMatch(x, regexExpr, RegexOptions.IgnoreCase) &&
x.ToLower().Contains("msgtrait") &&
x.EndsWith(".xml"))
.ToList();
List<string> finalList = new List<string>();
foreach (string strFich in xmlColct)
{
if (colctNames.Any(item => strFich.ToLower().Contains(item.ToLower())))
{
finalList.Add(strFich);
}
}
return finalList;
// include some kind of linq method to get only what I want instead of stripping down the list...
}
}
基本上需要获取与ABN_msgTrait.xml
匹配的服务器上的任何文件。我的需求是,如果用户只搜索ORL
,UQM
或BLABLABLA
,则该方法仅获取所需的列表,而不是删除所有结果我需要什么请注意,列表xmlColct
是一个路径列表,其中可能包含ORL
名称,如下所示:ORL_msgtrait.xml
。
所以我的问题是:有没有办法将我在linq请求中执行的foreach合并到避免必须检索所有xml然后删除不需要的xml?
答案 0 :(得分:1)
List<string> xmlColct = Directory.GetFiles(strPath, "*.*", SearchOption.AllDirectories)
.Where(x => Regex.IsMatch(x, regexExpr, RegexOptions.IgnoreCase) &&
x.ToLower().Contains("msgtrait") &&
x.EndsWith(".xml") &&
colctNames.Any(item => x.ToLower().Contains(item.ToLower())))
.ToList();
但如果你已经在使用正则表达式,你可以添加它:
Any
string.Join
的{{1}}部分,以便为colctNames