将MatchCollection转换为HashSet的最佳方法是什么?

3
我有以下代码来从一个输入文件中提取特定的标记:
string sLine = File.ReadAllText(ituffFile);
Regex rxp = new Regex(@"2_tname_(?<token>\S+)", RegexOptions.Compiled);
MatchCollection rxpMatches = rxp.Matches(sLine);

现在我想把包含我要查找的元素的MatchCollection转换成HashSet。

如何最快地实现这个目标?

以下是最佳方法吗?

HashSet<string> vTnames = new HashSet<string>();
foreach (Match mtch in rxpMatches)
{
    vTnames.Add(mtch.Groups["token"].Value);
}
2个回答

2

根据我的看法,你的代码很完美,因为似乎没有适合将MatchCollection转换为HastSet的方法。所以你使用的foreach循环的方式是完美的。


1
如果你正在寻找一个针对对象的Linq表达式:
Regex rxp = new Regex(@"2_tname_(?<token>\S+)", RegexOptions.Compiled);
MatchCollection rxpMatches = rxp.Matches(sLine);
HashSet<string> vTnames = 
  rxpMatches.Cast<Match> ().Aggregate (
    new HashSet<string> (),
    (set, m) => {set.Add (m.Groups["token"].Value); return set;});

当然,使用foreach的解决方案会稍微快一些。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接