Linq 返回带有字符串拆分索引的二维数组



我有一个文件夹,其中包含多个格式为NameIndex.Index的文件。我需要使用 Linq 返回的 2D 数组,其中 Name 是我的字符串,两个索引(都只有 1 个字符(是 2D 数组索引。

示例:Head4.2 将在我返回的数组中的 [4,2] 位置。

File[,] files = arrayWithAllFiles.Select(f => f.name.StartsWith(partName))
. // dont know how to continue
/*
result would look like, where the element is the File (not it's name):
| Head0.0    Head0.1   Head0.2 ... |
| Head1.0    Head1.1   Head1.2 ... |
*/

PS:也可以检查大于 9 的指数吗?

您可以使用正则表达式来解析文件名,这样您就不必担心数字大于 9。数字可以有多个数字。 例如

using System.Text.RegularExpressions;
/*
Pattern below means - one or more non-digit characters, then one or more digits,
then a period, then one or more digits. Each segment inside the parentheses will be one
item in the split array.
*/
string pattern = @"^(D+)(d+).(d+)$";
string name = "Head12.34";
var words = Regex.Split(name, pattern);
// Now words is an array of strings - ["Head", "12", "34"]

因此,对于您的示例,您可以尝试:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
string pattern = @"^(D+)(d+).(d+)$";
var indices = files.Select(f =>
Regex.Split(f.name, pattern).Skip(1).Select(w => System.Convert.ToInt32(w)).ToArray()).ToArray();
// Getting the max indices in each direction. This decides the dimensions of the array.
int iMax = indices.Select(p => p[0]).Max();
int jMax = indices.Select(p => p[1]).Max();
var pairs = Enumerable.Zip(indices, files, (index, file) => (index, file));
File[,] files = new File[iMax + 1, jMax + 1];
foreach (var pair in pairs){
files[pair.index[0], pair.index[1]] = pair.file;
}

我不太喜欢正则表达式,这就是为什么我建议以下解决方案,假设您的输入有效:

private static (string name, int x, int y) ParseText(string text)
{
var splitIndex = text.IndexOf(text.First(x => x >= '0' && x <= '9'));
var name = text.Substring(0, splitIndex);
var position = text.Substring(splitIndex).Split('.').Select(int.Parse).ToArray();
return (name, position[0], position[1]);
}
private static string[,] Create2DArray((string name, int x, int y)[] items)
{
var array = new string[items.Max(i => i.x) + 1, items.Max(i => i.y) + 1];
foreach (var item in items)
array[item.x, item.y] = item.name;
return array;
}

然后你可以像这样调用这些函数:

var files = new[] { "head1.0", "head4.1", "head2.3" };
var arr = Create2DArray(files.Select(ParseText).ToArray());

最新更新