c# - 如何将 List<string> 转换为 IEnumerator<string>

标签 c# linq

我知道 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/

相关文章:

c# - IN 语句中的 Datacontext ExecuteCommand 参数

c# - 输入字符串的格式不正确

c# - 如何处理Process类返回的错误?

c# - asp.net文件上传和文件读取(图片)

c# - 如何在两个地方获得锁,但在一个地方释放锁?

asp.net-mvc - Entity Framework Include OrderBy随机生成重复数据

c# - 使用 C# Linq Lambda 将两个对象的字段合并为一个,最好不要使用匿名对象

c# - Linq 在单次迭代中选择和聚合

C#和MYSQL数据库在另一台电脑上

c# - C#中如何从串口读取字节数组