读取带[]分隔块的文本文件并构建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:
First, let's align on assumptions (adjust if your file differs!):
Your text file has blocks marked by
[EnumValue](each matching aMyEenum 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
MyEenum (one slot perMyEvalue) - 2nd dimension: All entries under that
MyEblock - 3rd dimension: Split parts of a single entry (two enum attributes + the entry content)
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.
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.
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]}"); } }
- Separator Detection: The regex
^\[(.*)\]$reliably matches lines wrapped in square brackets. AddRegexOptions.IgnoreCasetoRegex.Matchif your separators don't match enum casing exactly. - Jagged Array Syntax:
string[][][]lets eachMyEblock have a different number of entries (unlike fixed multidimensional arrays likestring[,,]). 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

