You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

读取带[]分隔块的文本文件并构建string[][][]结构的问题

Hey there! Let's work through this problem together—sounds like you need to parse a text file with block separators tied to your MyE enum and build a string[][][] for easy lookup. Here's a step-by-step breakdown with code to fix both your separator detection and array syntax issues:

1. Clarify the File Structure & Array Mapping

First, let's align on assumptions (adjust if your file differs!):

Your text file has blocks marked by [EnumValue] (each matching a MyE enum entry), with each line inside a block being a single entry. Each entry itself is split by two enum-based attributes (e.g., EnumAVal|EnumBVal|ActualContent).

The string[][][] you want maps like this:

  • 1st dimension: Index of your MyE enum (one slot per MyE value)
  • 2nd dimension: All entries under that MyE block
  • 3rd dimension: Split parts of a single entry (two enum attributes + the entry content)
2. Step 1: Detect Separators & Group Entries

We'll read the file line-by-line, use regex to spot [XXX] separators, and map them to your MyE enum. We'll use a dictionary to temporarily group entries by their corresponding MyE value before building the array.

3. Step 2: Build the 3D String Array

Since string[][][] is a jagged array (not a fixed multidimensional array), it's perfect for handling blocks with varying numbers of entries. We'll convert our grouped entries into this structure for easy indexing.

4. Full Code Example (C#)

Assuming you have your enums defined like this:

// Your main enum tied to block separators
public enum MyE
{
    UserData,
    ProductInfo,
    OrderHistory
}

// The two enums used as entry attributes
public enum EntryAttr1
{
    Active,
    Inactive
}

public enum EntryAttr2
{
    Digital,
    Physical
}

Here's the parsing and array-building logic:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class FileParser
{
    public static string[][][] ParseFile(string filePath)
    {
        // Initialize a dictionary to hold entries per MyE enum value
        var enumEntryGroups = new Dictionary<MyE, List<string[]>>();
        foreach (MyE enumVal in Enum.GetValues(typeof(MyE)))
        {
            enumEntryGroups[enumVal] = new List<string[]>();
        }

        MyE currentBlock = default;
        bool foundFirstBlock = false;

        foreach (string rawLine in File.ReadLines(filePath))
        {
            string line = rawLine.Trim();
            if (string.IsNullOrEmpty(line)) continue; // Skip empty lines

            // Match lines that are [EnumValue] separators
            var separatorMatch = Regex.Match(line, @"^\[(.*)\]$");
            if (separatorMatch.Success)
            {
                // Convert the separator text to MyE enum
                if (Enum.TryParse<MyE>(separatorMatch.Groups[1].Value, out MyE parsedEnum))
                {
                    currentBlock = parsedEnum;
                    foundFirstBlock = true;
                }
                else
                {
                    Console.WriteLine($"Warning: Ignoring invalid block separator: {line}");
                }
                continue;
            }

            // Skip content before the first valid block
            if (!foundFirstBlock)
            {
                Console.WriteLine($"Warning: Ignoring content before first block: {line}");
                continue;
            }

            // Split the entry into its 3 parts (adjust the separator to match your file!)
            string[] entryParts = line.Split('|');
            if (entryParts.Length == 3)
            {
                enumEntryGroups[currentBlock].Add(entryParts);
            }
            else
            {
                Console.WriteLine($"Warning: Invalid entry format (needs 3 parts): {line}");
            }
        }

        // Convert the dictionary to the jagged 3D array
        string[][][] result = new string[Enum.GetValues(typeof(MyE)).Length][][];
        foreach (MyE enumVal in Enum.GetValues(typeof(MyE)))
        {
            int enumIndex = (int)enumVal;
            result[enumIndex] = enumEntryGroups[enumVal].ToArray();
        }

        return result;
    }

    // Example usage
    public static void Main()
    {
        string[][][] data = ParseFile("your-file-path.txt");
        
        // Retrieve an entry: MyE.ProductInfo -> 2nd entry -> its attributes/content
        string[] targetEntry = data[(int)MyE.ProductInfo][1];
        Console.WriteLine($"Attribute 1: {targetEntry[0]}, Attribute 2: {targetEntry[1]}, Content: {targetEntry[2]}");
    }
}
5. Key Fixes & Tips
  • Separator Detection: The regex ^\[(.*)\]$ reliably matches lines wrapped in square brackets. Add RegexOptions.IgnoreCase to Regex.Match if your separators don't match enum casing exactly.
  • Jagged Array Syntax: string[][][] lets each MyE block have a different number of entries (unlike fixed multidimensional arrays like string[,,]). This fits your use case perfectly.
  • Error Handling: The code includes warnings for invalid separators, malformed entries, and content before the first block—adjust this logging to fit your needs (e.g., throw exceptions instead).
  • Entry Splitting: Replace Split('|') with your actual entry separator (comma, tab, etc.) based on how your entries are formatted.

If your file structure is different (e.g., entries are split by something other than a delimiter), just tweak the entry parsing part!

内容的提问来源于stack exchange,提问作者ag4w

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 06:18:05