开发者

What is the best way to convert a MatchCollection to a HashSet?

I have the following code to extract specific tokens from an input file

string sLine = File.ReadAllText(ituffFile);
Regex rxp = new Regex(@"2_tname_(?<token>\S+)", RegexOptions.Compiled);
MatchCollection rxpMatches = rxp.Matches(sLine);

Now i want to convert the MatchCollection, which holds the elements, i'm looking for to a HashSet.

开发者_运维问答

What is the fastest way to achieve this?

Is the following the best way?

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


Yeah according to me your code is perfect because there is not any suitable casting seems for MatchCollection to HastSet.So the way you are following using foreach loop is perfect..


If you're looking for a Linq-to-objects expression:

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;});

Of course the foreach solution is a little faster.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜