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

C# 4.0 将MatchCollection转换为HashSet的最佳方法是什么?,c#-4.0,C# 4.0,我有以下代码从输入文件中提取特定标记 string sLine = File.ReadAllText(ituffFile); Regex rxp = new Regex(@"2_tname_(?<token>\S+)", RegexOptions.Compiled); MatchCollection rxpMatches = rxp.Matches(sLine); string sLine=File.ReadAllText(iTufFile); Regex rxp=新的Regex(

我有以下代码从输入文件中提取特定标记

string sLine = File.ReadAllText(ituffFile);
Regex rxp = new Regex(@"2_tname_(?<token>\S+)", RegexOptions.Compiled);
MatchCollection rxpMatches = rxp.Matches(sLine);
string sLine=File.ReadAllText(iTufFile);
Regex rxp=新的Regex(@“2_tname_(?\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);
}
HashSet vTnames=newhashset();
foreach(rxpMatches中的匹配mtch)
{
vTnames.Add(mtch.Groups[“token”].Value);
}

是的,根据我的说法,您的代码是完美的,因为没有任何适合MatchCollection到HastSet的类型转换。因此,您使用foreach循环的方法是完美的。

如果您正在寻找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;});
Regex rxp=新的Regex(@“2_tname_(?\S+),RegexOptions.Compiled);
MatchCollection rxpMatches=rxp.Matches(sLine);
HashSet vTnames=
rxpMatches.Cast().Aggregate(
新的HashSet(),
(set,m)=>{set.Add(m.Groups[“token”].Value);返回set;});
当然,foreach解决方案要快一点