在 C# 中对 MatchCollection 进行排序
我正在尝试用 C# 重写 TCL 代码。需要关注的代码如下:
set list [regexp -all -inline -line {.+\d+.+\d+} $string]
在这种情况下, regexp 过程返回字符串中所有匹配项的列表,之后我根据字符串末尾的数值使用另一个表达式对该字符串列表进行排序:
set sortedList [lsort -decreasing -integer -index end $list]
问题是,如何在C#中实现同样的效果?我尝试了以下操作:
MatchCollection mc = Regex.Matches(inputString, regexPattern, RegexOptions.Multiline);
然而,正如我发现的,我无法直接在 C# 中对 matchcollection 进行排序,因此我将每个匹配项复制到一个数组中:
string[] arrayOfMatches = new string[mc.Count];
for (int i = 0; i < mc.Count; i++)
{
arrayOfMatches[i] = mc[i].Groups[1].Value;
}
但是,当我尝试对 arrayOfMatches 数组进行排序时,我看不到可用的 Sort 方法。我错过了什么?我正在朝着正确的方向前进吗?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要对数组进行排序,请使用静态 Array.Sort() 方法。也就是说,要对匹配项进行排序,您需要定义一个 IComparer。也许更简单的方法是使用一点 linq-fu:
排序将是组数组中按升序排序的第二项的值。它的工作原理是 .Select 创建您想要的投影,而 .OrderBy 对堆栈进行排序。
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: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.
Array.Sort()
方法< /a> 是静态的,因此您必须这样调用它:其中
comparison
是可以比较两个字符串的委托,或者是可以比较的IComparer
的实现做同样的事情。但使用 LINQ 可能更容易:
这假设整个
value
是数字。如果我理解正确并且您想从字符串末尾获取数值,则必须添加代码来执行此操作。The
Array.Sort()
method is static, so you have to call it like this:Where
comparison
is either a delegate that can compare two strings or an implementation ofIComparer<T>
that can do the same.But it might be easier to use LINQ:
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.