无休止地重复列表(使用无限重复序列压缩有限列表) [英] Repeat list endlessly (Zip a finite list with an Infinite repeating sequence)
问题描述
UserList
是字典的列表,例如:
UserList
is a list of dictionaries, like:
[
{Name:"Alex",Age:25},
{Name:"Peter",Age:35},
{Name:"Muhammad",Age:28},
{Name:"Raul",Age:29}
]
RowColorList
是颜色列表:[#bcf,#fc0]
新的UserList
应为每个名称包含一个RowColor
,依次从RowColorList
提取:
The new UserList
should contain one RowColor
for every name, taken in sequence from RowColorList
:
[
{Name:"Alex",Age:25,RowColor:#bcf},
{Name:"Peter",Age:35,RowColor:#fc0},
{Name:"Muhammad",Age:28,RowColor:#bcf},
{Name:"Raul",Age:29,RowColor:#fc0}
]
我尝试了以下代码:
UserList.Zip(RowColorList,(user,color) => user.Add("RowColor",color))
使用此代码,新的UserList
将仅包含与RowColorList
中一样多的条目.每当可用的颜色用完时,我希望他从RowColorList
的开头重新开始.怎么样?
With this code, the new UserList
will only contain as many entries as are in RowColorList
. I would like him to start from the beginning of RowColorList
again, whenever the available colors are used up. How?
推荐答案
通过使用yield return
作为惰性生成器:
You can create a function to return an infinite enumerable of Color
/ string
(or whatever the type of RowColor
is), by using yield return
as a lazy generator:
public IEnumerable<Color> InfiniteColors()
{
while (true)
{
foreach (var color in RowColors)
{
yield return color;
}
}
}
然后可以将其与任何Linq IEnumerable
扩展方法(例如Zip
)一起使用.
This can then be used with any of the Linq IEnumerable
extension methods such as Zip
.
UserList.Zip(InfiniteColors(),(user,color) => user.Add("RowColor",color))
编辑-说明
InfiniteColors
不挂起的原因是因为状态机将在每个结果之后让回给调用者,并且Zip将在第一个可枚举的对象终止时终止,这是因为另一个压缩的集合是有限的(即UserList
)
The reason why InfiniteColors
doesn't hang is because the state machine will yield back to the caller after each result, and Zip will terminate on the first enumerable to complete, which is because the other collection being zipped is finite (i.e. UserList
)
很明显,您不应该尝试将InfiniteColors
和Zip
本身枚举,也不要尝试实现InfiniteColors
,即不要调用InfiniteColors.ToList()
或类似的方法:-):
Obviously you shouldn't try and Zip
the InfiniteColors
enumerable with itself, nor should you try and materialize InfiniteColors
, i.e. don't call InfiniteColors.ToList()
or such :-):
这篇关于无休止地重复列表(使用无限重复序列压缩有限列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!