C#实现文本文件首元素相同行的字段拼接方案咨询
Got it, let's get this sorted for you! Here's a complete C# implementation that handles the grouping, cleaning, and formatting exactly as your requirements specify:
using System; using System.Collections.Generic; using System.IO; using System.Text; class Program { static void Main(string[] args) { string path = "your-file-path-here.txt"; // Replace with your actual file path ProcessFile(path); } static void ProcessFile(string path) { using (StreamReader reader = new StreamReader(path)) { string fileContent = reader.ReadToEnd(); string[] lines = fileContent.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries); // Dictionary to group unique second fields by the cleaned first field Dictionary<string, HashSet<string>> groupedData = new Dictionary<string, HashSet<string>>(); foreach (string line in lines) { string[] segments = line.Split(',', StringSplitOptions.RemoveEmptyEntries); if (segments.Length < 2) continue; // Skip lines that don't have at least two fields // Clean the first segment: strip leading zeros, default to "0" if all zeros string firstKey = segments[0].TrimStart('0'); firstKey = string.IsNullOrEmpty(firstKey) ? "0" : firstKey; // Clean the second segment: strip leading zeros, ignore if it becomes empty (all zeros) string secondValue = segments[1].TrimStart('0'); if (string.IsNullOrEmpty(secondValue)) continue; // Add the value to the corresponding group if (!groupedData.ContainsKey(firstKey)) { groupedData[firstKey] = new HashSet<string>(); } groupedData[firstKey].Add(secondValue); } // Build the final output string StringBuilder outputBuilder = new StringBuilder(); foreach (var group in groupedData) { outputBuilder.Append("HI:").Append(group.Key); if (group.Value.Count > 0) { outputBuilder.Append(",").Append(string.Join(",", group.Value)); } outputBuilder.AppendLine(); } // Print the result or write to a file Console.WriteLine(outputBuilder.ToString().TrimEnd()); // Uncomment below to save to a file: // File.WriteAllText("formatted-output.txt", outputBuilder.ToString().TrimEnd()); } } }
Key Details Explained:
- Grouping Logic: We use a
Dictionarypaired with aHashSetto automatically handle grouping by the first field and ensure no duplicate second fields are included (even if your input has repeated lines). - Field Cleaning:
- The first field is stripped of leading zeros—if the result is empty (like "00000"), we default to "0" to avoid blank keys.
- The second field is also stripped of leading zeros; if it becomes empty (meaning it was all zeros, like "00000"), we skip adding it to the group (matching your example where these values are omitted from the output).
- Output Formatting: We loop through each group to build lines in the
HI:key,value1,value2,...format you need.
内容的提问来源于stack exchange,提问作者Cicciux
相关产品推荐
相关产品推荐

