重写这个的foreach产量到LINQ的收益呢? [英] Rewrite this foreach yield to a linq yield?

查看:146
本文介绍了重写这个的foreach产量到LINQ的收益呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下的code(上下文范围缩小到保持的问题包括但不限于)

Say I have the following code (context narrowed down as to keep the question scope limited)

public static IEnumerable<Color> GetThemColors(){
	var ids = GetThePrimaryIds();
	foreach (int id in ids){
		yield return GetColorById(id);
	}
	ids = GetTheOtherIds();
	foreach (int id in ids){
		yield return GetOtherColorsById(id);
	}
}

我想将它们改写为这样的事情(这当然不编译

I would like to rewrite them to something like this (which off course doesn't compile

public static IEnumerable<Color> GetThemColors(){
	GetThePrimaryIds().Select(id=>yield return GetColorById(id));
	GetTheOtherIds().Select(id=>yield return GetOtherColorsById(id));		
}

关键的一点是,在我的第一个片段,我有两个的foreach枚举屈服,我不知道该怎么办的LINQ没有失去我的懒加载功能。

The key point being that in my first snippet I have two foreach enumerators yielding, which I don't know how to do in linq without loosing my lazy-loading features.

推荐答案

您想要 Concat的

return GetThePrimaryIds().Select(id => GetColorById(id)).Concat(
    GetTheOtherIds().Select(id => GetOtherColorsById(id)));

另外请注意,你并不需要在lambda表达式收益率回报

这篇关于重写这个的foreach产量到LINQ的收益呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆