猿问

锯齿状到多维数组

我和一位同事目前正在参与一系列编码挑战。

然而,我们喜欢让事情变得更有趣,并把我们的答案打下来(是的,我知道,C# 不是最棒的高尔夫语言)

我们最近的一个涉及旋转一个立方体 (int[,])。所以最终我们想出了一个赌注,如果我能做到这一点,他就会请我吃午饭,反之亦然。

经过许多退格和我妈妈讨厌听我说的话,我终于明白了,或者我是这么想的。

我最终得到了 int[][]。

据我所知,没有简单的方法可以将其转换为 int[,]。所以我问它是否真的可以在一行中实现。

编辑 1

我会发布我的源代码,但是我的同事可以找到它,我可能会失去免费午餐。


胡说叔叔
浏览 167回答 3
3回答

猛跑小猪

您至少需要两行,一行用于声明结果数组,另一行用于实际复制数据。您可以首先将数组数组展平为单个数组,然后使用Buffer.BlockCopy将所有数据复制到结果数组。下面是一个例子:var source = new int[][] {&nbsp; &nbsp; new int[4]{1,2,3,4},&nbsp; &nbsp; new int[4]{5,6,7,8},&nbsp; &nbsp; new int[4]{1,3,2,1},&nbsp; &nbsp; new int[4]{5,4,3,2}};var expected = new int[4,4] {&nbsp; &nbsp; {1,2,3,4},&nbsp; &nbsp; {5,6,7,8},&nbsp; &nbsp; {1,3,2,1},&nbsp; &nbsp; {5,4,3,2}};var result = new int[4, 4];// count = source.Length * source[0].Length * sizeof(int) = 64, since BlockCopy is byte based// to be dynamically you could also use System.Runtime.InteropServices.Marshal.SizeOf(source[0][0]) instead of sizeof(int)Buffer.BlockCopy(source.SelectMany(r => r).ToArray(), 0, result, 0, 64);result.Dump("result");expected.Dump("expected");结果:如果您坚持要花哨:您可以BlockCopy使用委托动态调用该委托返回,Object以便您可以将其用于匿名类的分配,这显然符合您的规则精神,并将所有内容包装到一个集合中,以便您以这样的单行怪物结尾:var&nbsp;result&nbsp;=&nbsp;new[]{&nbsp;new&nbsp;int[4,&nbsp;4]&nbsp;}.Select(x&nbsp;=>&nbsp;new&nbsp;{&nbsp;r&nbsp;=&nbsp;x,&nbsp;tmp&nbsp;=&nbsp;Delegate.CreateDelegate(typeof(Action<Array,&nbsp;int,&nbsp;Array,&nbsp;int,&nbsp;int>),&nbsp;typeof(Buffer).GetMethod("BlockCopy")).DynamicInvoke(new&nbsp;Object[]{source.SelectMany(r&nbsp;=>&nbsp;r).ToArray(),&nbsp;0,&nbsp;x,&nbsp;0,&nbsp;64})}).First().r;

PIPIONE

如果您被允许使用Func<>和 lambda,您当然可以这样做并进行通用扩展来转换您正在调用它的对象。/// <typeparam name="T">Output type</typeparam>/// <typeparam name="U">Calling type</typeparam>/// <param name="obj">object to pipe</param>/// <param name="func">blackbox function</param>/// <returns>whatever</returns>public static T ForThis<T,U> (this U obj, Func<U,T> func){&nbsp; &nbsp; return func(obj);}有了这个,您应该能够通过执行以下操作将 int[,] 转换为 int[][]:int[][] output = input.ForThis<int[][], int[,]>((obj) =>{&nbsp; &nbsp; // transform obj == input of type int[,] into int[][]&nbsp; &nbsp; throw new NotImplementedException();});虽然我承认这个解决方案真的感觉像是在作弊,因为您只是将多行转换包装到 lambda 中。
随时随地看视频慕课网APP
我要回答