我知道 List 和 IEnumerator 的基础知识,但我仍然对此感到困惑。我想从字符串中搜索有效的 URL。我可以通过 LINQ 提取有效的 URL,但我想使用 MatchCollection 的 IEnumerator GetEnumerator()。
string url = @"http://www.ms.com http://www.hemelix.com http://www.cgi.com";
string pattern = @"http://(www\.)?([^\.]+)\.com";
List<string> result = new List<string>();
MatchCollection myMatches = Regex.Matches(url, pattern);
result = (
from System.Text.RegularExpressions.Match m in myMatches
select m.Value
).ToList<string>();
var result2 = from Match m in myMatches
select m.Value;
foreach (var item in result2)
{
Console.WriteLine(item.ToString());
}
// Does the following code work in this case??
result = (List<string>)myMatches.GetEnumerator();
// OR the following
IEnumerator<string> enumerator = (IEnumerator<string>) (myMatches.GetEnumerator());
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
最佳答案
您不能将 List 转换为 IEnumerator,这是完全不同的事情。 List 实现 IEnumerable,而 Enumerator 用于迭代 IEnumerable。
您的(更正后的)代码
IEnumerator enumerator = myMatches.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
和
一样foreach (var item in myMatches)
{
Console.WriteLine(item);
}
关于c# - 如何将 List<string> 转换为 IEnumerator<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109824/