如果您正在进行大量查找并且速度比内存更重要,您可能希望处理一次文件并将信息放入字典中。这样查找速度非常快,您只需读取文件一次。
这里有一些代码会像你给出的例子那样解析数据:
class Program
{
static void Main(string[] args)
{
string filename = "example.txt";
Dictionary<string, int[][]> myDictionary = new Dictionary<string, int[][]>();
BuildMyDataDictionary(filename, myDictionary);
//lookup via key
int x = 20;
int y = 180;
string key = string.Format("{0}.{1}", x, y);
int[][] values = myDictionary[key];
//print the values to check
foreach (int[] array in values)
foreach (int i in array)
Console.Write(i + ", ");
Console.WriteLine();
Console.ReadKey();
}
private static void BuildMyDataDictionary(string filename, Dictionary<string, int[][]> myDictionary)
{
using (StreamReader r = new StreamReader(filename))
{
string line = r.ReadLine();
// read through the file line by line and build the dictionary
while (line != null)
{
Regex regx = new Regex(@"//\s*H\-(\d*)\w(\d*)");
Match m = regx.Match(line);
if (m.Success)
{
// make a key of the two parts int 1 and int2 separated by a "."
string key = string.Format("{0}.{1}", m.Groups[1], m.Groups[2]);
// continue reading the block
List<int[]> intList = new List<int[]>();
line = r.ReadLine();
while (!Regex.IsMatch(line, @"^\s*\}"))
{
Regex regex = new Regex("[{},]");
intList.Add(regex.Replace(line, " ").Trim().Split(new char[] { ' ' }).Select(int.Parse).ToArray());
line = r.ReadLine();
}
myDictionary.Add(key, intList.ToArray());
}
line = r.ReadLine();
}
}
}
}
我测试的示例文件是:
{ // H-20e180a.wav
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,730,4751,3861},
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,}
}
{ // H-21e181a.wav
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,730,4751,3861},
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,}
{-7,5,-4,-1,-9,2,-5,-1,2,-12,12,-33,34,-48,41,-40,16,20,730,4751,3861},
}
我从上面的 jltrem 借用了 int[] 的解析和创建。