拼合在C#Ruby的方法 [英] Flatten Ruby method in C#
本文介绍了拼合在C#Ruby的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该怎么办了Ruby方法拼合红宝石法 C#中。这种方法平坦交错数组到一个一维数组。
例如:
S = [1,2,3]#=> [1,2,3]
T = [4,5,6,[7,8]]#= GT; [4,5,6,[7,8]
一个= [S,T,9,10]#= GT; [[1,2,3],[4,5,6,[7,8],9,10]
a.flatten#=> [1,2,3,4,5,6,7,8,9,10
解决方案
递归解决方案:
的IEnumerable展平(IEnumerable的数组)
{
的foreach(数组VAR项)
{
如果(产品IEnumerable的)
{
的foreach(在平展VAR子项目((IEnumerable的)项))
{
产生回报子项目;
}
}
其他
{
产生回报的项目;
}
}
}
编辑1:
乔恩解释了为什么评论它不可能是一个通用的方法,一起来看看吧!
编辑2:
马特建议使它的扩展方法。在这里你去,只需更换的第一行:
公共静态的IEnumerable展平(这IEnumerable的数组)
和您可以使用它是这样的:
的foreach(在myArray.Flatten()VAR项){...}
How can I do the Ruby method "Flatten" Ruby Method in C#. This method flattens a jagged array into a single-dimensional array.
For example:
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
解决方案
Recursive solution:
IEnumerable Flatten(IEnumerable array)
{
foreach(var item in array)
{
if(item is IEnumerable)
{
foreach(var subitem in Flatten((IEnumerable)item))
{
yield return subitem;
}
}
else
{
yield return item;
}
}
}
EDIT 1:
Jon explains in the comments why it cannot be a generic method, take a look!
EDIT 2:
Matt suggested making it an extension method. Here you go, just replace the first line with:
public static IEnumerable Flatten(this IEnumerable array)
and you can use it like this:
foreach(var item in myArray.Flatten()) { ... }
这篇关于拼合在C#Ruby的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文