Reputation: 45
I am trying to rewrite TCL code in C#. The code of concern is the following:
set list [regexp -all -inline -line {.+\d+.+\d+} $string]
In this case the regexp procedure returns a list of all matches in the string after which I am sorting this list of strings with another expression based on a numeric value in the end of the string:
set sortedList [lsort -decreasing -integer -index end $list]
The question is, how to achieve the same in C#? I tried the following:
MatchCollection mc = Regex.Matches(inputString, regexPattern, RegexOptions.Multiline);
As I found however, I cannot sort a matchcollection directly in C# so I copied every match to an array:
string[] arrayOfMatches = new string[mc.Count];
for (int i = 0; i < mc.Count; i++)
{
arrayOfMatches[i] = mc[i].Groups[1].Value;
}
However, when I try to sort the arrayOfMatches array, I do not see the Sort method available. What am I missing and am I moving in the right direction? Thanks!
Upvotes: 1
Views: 3647
Reputation: 15673
To sort arrays, you use the static Array.Sort()
method. That said, to sort the matches you would need to define an IComparer. Perhaps an easier way to do this would be to use a little linq-fu:
var mc = Regex.Matches(input, patter);
var matches = new Match[mc.Count];
mc.CopyTo(matches, 0);
var sorted = matches
.Select(x => x.Groups[1].Value)
.OrderBy(x => x);
Sorted will be the value of 2nd item the groups array sorted in ascending order. How it works is the .Select creates the projection you want and the .OrderBy sorts the stack.
Upvotes: 3
Reputation: 244777
The Array.Sort()
method is static, so you have to call it like this:
Array.Sort(arrayOfMatches, comparison);
Where comparison
is either a delegate that can compare two strings or an implementation of IComparer<T>
that can do the same.
But it might be easier to use LINQ:
var matches =
from Match m in mc
let value = m.Groups[1].Value
let numericValue = int.Parse(value)
orderby numericValue descending
select value;
This assumes the whole value
is the number. If I understand you correctly and you want to get a numeric value from the end of the string, you would have to add code to do that.
Upvotes: 1