我们说我有一个二维浮动阵列
float [,] myfloats = new float[10, 10]
FillWithValues(myfloats);
如何使用随机评估方法将此二维浮点数组转换为二维bool数组?
我希望这样的事情:
bool[,] mybools;
mybools = myfloats.Select(myfloat => Evaluate(myfloat));
但这不起作用......
答案 0 :(得分:3)
不幸的是,多维数组与LINQ不兼容,有点难以处理。我不认为这种双循环解决方案有办法解决方法:
bool[,] mybools = new bool[myfloats.GetLength(0), myfloats.GetLength(1)];
for (int x = 0; x<myfloats.GetLength(0); x++)
for(int y=0; y<myfloats.GetLength(1); y++)
mybools[x,y] = Evaluate(myfloats[x,y]);
Array.GetLength(Int32)
为您提供特定维度中数组的大小。
答案 1 :(得分:1)
它不是特别有效,但有两种扩展方法可以做到这一点:
var floats = new float[3, 3] {
{ 1f, 2f, 3f },
{ 4f, 5f, 6f },
{ 7f, 8f, 9f }
};
Func<float, bool> floatToBool = f => f > 5f;
var bools =
floats
.ToJaggedArray()
.Select(array => array.Select(floatToBool).ToArray())
.ToArray()
.To2DArray();
请注意,您必须将其操作回数组&#34;数组&#34;回到2D阵列。
如果我们转换为可枚举的枚举而不是锯齿状数组,它会更好。然后它看起来像这样:
var bools =
floats
.ToEnumerableOfEnumerables()
.Select(array => array.Select(floatToBool))
.To2DArray();
第一部分的两种扩展方法是这样的:
[Pure, NotNull]
public static T[][] ToJaggedArray<T>([NotNull] this T[,] p2DArray) {
var height = p2DArray.GetLength(0);
var width = p2DArray.GetLength(1);
var result = new T[height][];
for (var row = 0; row < height; row++) {
result[row] = new T[width];
for (var col = 0; col < width; col++)
result[row][col] = p2DArray[row, col];
}
return result;
}
[Pure, NotNull]
public static T[,] To2DArray<T>([NotNull] this T[][] pJaggedArray) {
if (!pJaggedArray.Any() || !pJaggedArray[0].Any())
return new T[0, 0];
var height = pJaggedArray.Length;
var width = pJaggedArray[0].Length;
var result = new T[height, width];
for (var r = 0; r < height; r++) {
var subArray = pJaggedArray[r];
if (subArray == null || subArray.Length != width)
throw new InvalidOperationException("Jagged array was not rectangular.");
for (var c = 0; c < width; c++)
result[r, c] = subArray[c];
}
return result;
}
第二部分是这样的:
[Pure, NotNull]
public static IEnumerable<IEnumerable<T>> ToEnumerableOfEnumerables<T>(
[NotNull] this T[,] p2DArray
) {
var height = p2DArray.GetLength(0);
for (var row = 0; row < height; row++)
yield return p2DArray.GetPartialEnumerable(row);
}
[Pure, NotNull]
public static IEnumerable<T> GetPartialEnumerable<T>(
[NotNull] this T[,] p2DArray,
int pRow
) {
var width = p2DArray.GetLength(1);
for (var col = 0; col < width; col++)
yield return p2DArray[pRow, col];
}
[Pure, NotNull]
public static T[,] To2DArray<T>(
[NotNull] this IEnumerable<IEnumerable<T>> pJaggedArray
) {
if (!pJaggedArray.Any() || !pJaggedArray.First().Any())
return new T[0, 0];
var height = pJaggedArray.Count();
var width = pJaggedArray.First().Count();
var result = new T[height, width];
var r = 0;
foreach (var subArray in pJaggedArray) {
if (subArray == null || subArray.Count() != width)
throw new InvalidOperationException("Jagged array was not rectangular.");
var c = 0;
foreach (var item in subArray)
result[r, c++] = item;
r += 1;
}
return result;
}