Exemple #1
0
        public static IEnumerable <T> FilterObjectsByNames <T>(IEnumerable <T> items, IList <string> patterns, Func <T, string> get_name, bool ignorecase, FilterAction action)
        {
            if (patterns == null || patterns.Count < 1)
            {
                // nothing to filter just return the items
                foreach (T item in items)
                {
                    yield return(item);
                }
            }
            else
            {
                // Create the caches for fast matches of regexes
                var regexes = new List <System.Text.RegularExpressions.Regex>();

                var compare    = ignorecase ? StringComparer.InvariantCultureIgnoreCase : StringComparer.InvariantCulture;
                var nonregexes = new HashSet <string>(compare);

                foreach (var pattern in patterns)
                {
                    if (WildcardHelper.ContainsWildcard(pattern))
                    {
                        // If it contains a wildcard transform it into a regex
                        var regex = WildcardHelper.GetRegexForWildcardPattern(pattern, ignorecase);
                        regexes.Add(regex);
                    }
                    else
                    {
                        // if it doesn't contain a wildcard then perform simple string equality
                        nonregexes.Add(pattern);
                    }
                }

                // the caches are set up, let's process each item

                foreach (var item in items)
                {
                    string name = get_name(item);

                    // does it match any of the patterns
                    // we test nonregexes first on the assumption that it's faster than checking regexes
                    bool matches = (nonregexes.Contains(name)) || (regexes.Any(regex => regex.IsMatch(name)));

                    if (action == FilterAction.Exclude && !matches)
                    {
                        // For exclude, non-match means this is a desired item so yield it
                        yield return(item);
                    }
                    else if (action == FilterAction.Include && matches)
                    {
                        // For include, match means this is a desired item so yield it
                        yield return(item);
                    }
                }
            }
        }
Exemple #2
0
 public static IEnumerable <string> ExcludeByName(IEnumerable <string> items, IList <string> pattens, bool ignorecase)
 {
     return(WildcardHelper.FilterObjectsByNames(items, pattens, System.IO.Path.GetFileName, ignorecase, FilterAction.Exclude));
 }