【发布时间】:2015-05-19 08:10:10
【问题描述】:
我编写了一个方法,它从随机文本文件中获取以“b”开头的单词并返回一个 IEnumerable。它必须与收益回报一起使用。
问题是我不知道如何结合 Ienumerable 和 yield return 编写这样的方法。
这是我到目前为止得到的: GetWords.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace week3
{
class GetWords : IEnumerable<String>
{
private String[] getWords;
public GetWords()
{
}
public IEnumerator<String> GetEnumerator()
{
try
{
String path = @"C:\Users\Lilly\Downloads\randomtext.txt";
foreach (String word in getWords (path, s => s.StartsWith("b")))
Console.Write("{0}; ", word);
}
catch (Exception ex)
{
Console.WriteLine("wrong path");
}
yield return word;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
【问题讨论】:
-
你忘了说我猜的问题。
-
你需要在try块外声明和初始化你的变量
word才能在try块外返回它。 -
为什么需要
yield?使用LINQ,您只需返回.Where()调用即可。
标签: c# text-files ienumerable yield-return