我有一个包含多个文件的文件夹,格式为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?
答案 0 :(得分:0)
您可以使用Regex解析文件名,这样就不必担心数字大于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;
}
答案 1 :(得分:0)
我不是正则表达式的粉丝,这就是为什么我建议以下解决方案的原因,假设您的输入有效:
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());