Find multiple controls with by partially matching their name

后端 未结 3 1078
别那么骄傲
别那么骄傲 2021-01-19 10:14

I currently have 100+ labels, with names like:

labelNumber1 
labelNumber2 
labelNumber3 
labelNumber4 
....
labelLetter1
labelLetter2 
labelLetter3 
labelLet         


        
3条回答
  •  暖寄归人
    2021-01-19 11:17

    I know this is an old question, but I am here now, and:

    • The question asks about searching for multiple controls. This solution actually applies to any type of control.
    • OP was conflicted between using "Contains" or regex. I vote for regex! string.Contains is a bad idea for this kind of filter, since "CoolButton" has a "Button" in it too"

    Anyway, here is the code:

    public List FindByPattern(string regexPattern)
      where TControlType:Control
    {
       return Controls.OfType()
                      .Where(control => Regex.IsMatch(control.Name, regexPattern))
                      .ToList();
    }
    

    Usage:

    //some regex samples you can test out
    var startsWithLabel = $"^Label"; //Matches like .StartsWith()
    var containsLabel = "Label"; //Matches like .Contains()
    var startsWithLabelEndsWithNumber = "^Label.*\\d+&"; //matches Label8sdf12 and Label8
    var containsLabelEndsWithNumber = "Label.*\\d+&"; //matches MyLabelRocks83475, MyLabel8Rocks54389, MyLabel8, Label8
    var hasAnyNumber= "^CoolLabel\\d+$"; //matches CoolLabel437627
    
    var labels = FindByPattern

提交回复
热议问题