[英]Anonymous method with return type IEnumerable<T>
我正在為我的網站設計一個搜索引擎。 讀取搜索鍵並返回數據。
我的測試代碼:
public string ErrorMessage { get; set; }
private IEnumerable<TopicViewModels> GetTopics(List<TopicViewModels> topics)
{
foreach (var item in topics)
{
yield return item;
}
}
public async Task<IEnumerable<TopicViewModels>> Search(string key)
{
try
{
using (var db = new MyDbContext()) //EF
{
var topics = await db.Topics.Where(x => x.Title.Contains(key)).ToListAsync();
if (topics != null && topics.Count > 0)
{
return await Task.Run(() => GetTopics(topics));
}
ErrorMessage = "No topic was found.";
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
}
return null;
}
我正在尋找一種解決方案,我可以使用GetTopics
方法作為匿名方法。 無需創建新方法來獲取所有主題,因為不再有其他類/方法重用GetTopics
方法。
但我的問題是:匿名方法無法接受yield return
。 就像:
var topics = await db.Topics.Where(x => x.Title.Contains(key)).ToListAsync();
topics.ForEach(x =>
{
yield return x;
});
所以,我的問題是:還有另一種方法可以做得更好嗎?
更新:(基於@EricLippert評論)
public async Task<IEnumerable<TopicViewModels>> Search(string key)
{
using (var db = new MyDbContext())
{
var topics = await db.Topics.Where(x => x.Title.Contains(key)).ToListAsync();
if (topics != null && topics.Count > 0)
{
foreach (var topic in topics)
{
yield return topic;
}
}
ErrorMessage = "No topic was found.";
yield return null;
}
}
錯誤語法消息:
'TopicMaster.Search(string)'的主體不能是迭代器塊,因為
Task<IEnumerable<TopicViewModels>>
不是迭代器接口類型
更新2:
public async Task<IEnumerable<TopicViewModels>> Search(string key)
{
var topics = await new MyDbContext().Topics.Where(x => x.Title.Contains(key)).ToListAsync();
return topics != null && topics.Count > 0 ? topics : null;
}
這就是埃里克的說法:
if (topics != null && topics.Count > 0)
{
return topics;
}
具體來說, List<T>
實現IEnumerable<T>
,因此您只需返回列表即可。 不需要迭代器塊,匿名委托,或Task.Run
,或foreach
/ ForEach
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.