MatchCollection to List(Of String)

StewartBW 925 Reputation points
2024-07-22T19:52:17.1833333+00:00

Hello

Instead of:

For Each Match As Match In MatchCollection
    StringList.Add(Match.Value)
Next

Is there a shorter and faster way to add all element values in MatchCollection to the StringList which is list of string?

Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,666 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,491 Reputation points
    2024-07-22T19:56:05.3566667+00:00

    you can use linq for shorter source code, but it will not be faster. if there are larger number of matches adding code may make it faster.

    var size = MatchCollection.Count;
    if (size < 20) // use perf timing to optimize
    {
       foreach (var match in MatchCollection) StringList.Add(Match.Value);
    }
    else
    {
       var list = new List<string>(size); // preallocate
       foreach (var match in MatchCollection) list.Add(Match.Value);
       StringList.AddRange(list); // uses preallocation
    }
    

    note: compared to the performance of RegEx, this is probably not worth the effort. also be sure you are using precompiled regex expressions.

    0 comments No comments

0 additional answers

Sort by: Most helpful