c# - 如何解析具有交替名称行和整数列表的文本文件?

标签 c# arrays file

我需要读取一个文件并将该数据放入不同的数组中。

我的 .txt 文件如下所示:

w1;
1 2 3
w2;
3 4 5
w3;
4 5 6

我试过类似下面的方法:

int[] w1 = new int [3];
int[] w2 = new int [3];
int[] w3 = new int [3];

string v = "w1:|w2:|w3:";
foreach (string line in File.ReadAllLines(@"D:\\Data.txt"))
{
   string[] parts = Regex.Split(line, v);

我得到了那个字符串,但我不知道如何将它的每个元素切割成上面显示的数组。

最佳答案

而不是解析文件并将数组放入对应于硬编码名称的三个硬编码变量中 w1 , w2w3 , 我会删除硬编码并将文件解析为 Dictionary<string, int[]>像这样:

public static class DataFileExtensions
{
    public static Dictionary<string, int[]> ParseDataFile(string fileName)
    {
        var separators = new [] { ' ' };
        var query = from pair in File.ReadLines(fileName).Chunk(2)
                    let key = pair[0].TrimEnd(';')
                    let value = (pair.Count < 2 ? "" : pair[1]).Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s, NumberFormatInfo.InvariantInfo)).ToArray()
                    select new { key, value };
        return query.ToDictionary(p => p.key, p => p.value);
    }
}

public static class EnumerableExtensions
{
    // Adapted from the answer to "Split List into Sublists with LINQ" by casperOne
    // https://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq/
    // https://stackoverflow.com/a/419058
    // https://stackoverflow.com/users/50776/casperone
    public static IEnumerable<List<T>> Chunk<T>(this IEnumerable<T> enumerable, int groupSize)
    {
        // The list to return.
        List<T> list = new List<T>(groupSize);

        // Cycle through all of the items.
        foreach (T item in enumerable)
        {
            // Add the item.
            list.Add(item);

            // If the list has the number of elements, return that.
            if (list.Count == groupSize)
            {
                // Return the list.
                yield return list;

                // Set the list to a new list.
                list = new List<T>(groupSize);
            }
        }

        // Return the remainder if there is any,
        if (list.Count != 0)
        {
            // Return the list.
            yield return list;
        }
    }
}

您将按如下方式使用它:

var dictionary = DataFileExtensions.ParseDataFile(fileName);

Console.WriteLine("Result of parsing {0}, encountered {1} data arrays:", fileName, dictionary.Count);
foreach (var pair in dictionary)
{
    var name = pair.Key;
    var data = pair.Value;

    Console.WriteLine("  Data row name = {0}, values = [{1}]", name, string.Join(",", data));
}       

哪些输出:

Result of parsing Question49341548.txt, encountered 3 data arrays:
  Data row name = w1, values = [1,2,3]
  Data row name = w2, values = [3,4,5]
  Data row name = w3, values = [4,5,6]

注意事项:

sample 加工 .Net fiddle .

关于c# - 如何解析具有交替名称行和整数列表的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49341548/

相关文章:

php - 是否有一个有效的单线程序来获取目录中的第一个文件?

c# - 使用枚举项调用方法

c# - 如何在 Winform 中通过 Numpad 键控制按钮?

arrays - HTML 格式的报告 – 通过 PowerShell 发送电子邮件

javascript - 在javascript中以数组格式推出随机数

C++ : Read random line from text file

c - 我如何让这个程序循环主程序两次?

c# 可枚举类 - 与 VBA 兼容

c# - Aspx 下拉列表不显示最高值

c++ - 给奶牛的款待——自下而上的动态规划