linq任何相交包含的地方

时间:2016-08-08 15:25:30

标签: c# linq

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匹配的服务器上的任何文件。我的需求是,如果用户只搜索ORLUQMBLABLABLA,则该方法仅获取所需的列表,而不是删除所有结果我需要什么请注意,列表xmlColct是一个路径列表,其中可能包含ORL名称,如下所示:ORL_msgtrait.xml

所以我的问题是:有没有办法将我在linq请求中执行的foreach合并到避免必须检索所有xml然后删除不需要的xml?

1 个答案:

答案 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(); 

但如果你已经在使用正则表达式,你可以添加它:

  1. 以&#34; .xml&#34;
  2. 结尾
  3. 包含&#34; msgtrait&#34;在名称区域
  4. 以及包含Any string.Join的{​​{1}}部分,以便为colctNames
  5. 的可选值形成模式
相关问题