- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace FlattenTest
- {
- public static class ExtensionMethods
- {
- /// Ref.: Flatten Ruby method in C# - Stack Overflow
- /// http://stackoverflow.com/questions/197081/flatten-ruby-method-in-c
- private static IEnumerable FlattenAux(this IEnumerable array)
- {
- foreach (var item in array)
- {
- if (item is IEnumerable)
- {
- foreach (var subitem in FlattenAux((IEnumerable)item))
- {
- yield return subitem;
- }
- }
- else
- {
- yield return item;
- }
- }
- }
- /// Returns a one-dimensinal flattening of given array.
- public static System.Array Flatten(this System.Array array)
- {
- var al = new ArrayList(array.Length);
- foreach (var v in FlattenAux(array))
- al.Add(v);
- return al.ToArray(al[0].GetType());
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- float[, ,] p0 = new float[3,2,2];
- float[][][] p1 = new float[3][][] {
- new float[2][] { new float[2], new float[2] },
- new float[2][] { new float[2], new float[2] },
- new float[2][] { new float[2], new float[2] }
- };
- for (int i = 0; i < 3; ++i)
- for (int j = 0; j < 2; ++j)
- for (int k = 0; k < 2; ++k)
- p0[i, j, k] = p1[i][j][k] = 100 * i + 10 * j + k;
- float[] fp0 = (float[])p0.Flatten();
- for (int i = 0; i < fp0.Length; ++i)
- Console.Write("{0} ", fp0[i]);
- Console.WriteLine();
- float[] fp1 = (float[])p1.Flatten();
- for (int i = 0; i < fp1.Length; ++i)
- Console.Write("{0} ", fp1[i]);
- Console.WriteLine();
- }
- }
- }
Jun 6, 2010
C# : Flatten()のようなもの
RubyでいうArray#flattenに相当するメソッドがC#には無いということで、似たものを書いてみたのがこちら。System.Arrayに対する拡張メソッドとなっています。
Subscribe to:
Posts (Atom)