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

C#实现从TXT列表中根据字段值获取对应描述

Got it, here's a practical C# solution to solve your field-description lookup problem. Let's walk through how to implement this step by step.

Solution Overview

We'll create a reusable class that loads the field-description mappings from your TXT file into a dictionary for fast lookups, then add a method to return the formatted string when you input a field value.

Step-by-Step Implementation

First, here's the complete class to handle loading mappings and retrieving descriptions:

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

public class FieldDescriptionMapper
{
    // Dictionary to store our field-description pairs
    private readonly Dictionary<string, string> _fieldDescriptions;

    // Constructor that loads mappings from the TXT file
    public FieldDescriptionMapper(string txtFilePath)
    {
        if (!File.Exists(txtFilePath))
            throw new FileNotFoundException("Mapping file not found.", txtFilePath);
            
        _fieldDescriptions = LoadFieldMappings(txtFilePath);
    }

    // Private method to parse the TXT file and build the dictionary
    private Dictionary<string, string> LoadFieldMappings(string filePath)
    {
        var mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        // Use OrdinalIgnoreCase if you want case-insensitive lookups (e.g., "20d" works the same as "20D")

        foreach (var line in File.ReadAllLines(filePath))
        {
            // Skip empty lines or comment lines (if you add comments later)
            if (string.IsNullOrWhiteSpace(line) || line.StartsWith("//"))
                continue;

            // Split each line into the field part and description part
            var lineParts = line.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries);
            if (lineParts.Length != 2)
                continue; // Skip lines that don't match the expected format

            var fieldFullPart = lineParts[0].Trim();
            var description = lineParts[1].Trim();

            // Extract the actual field name (strip "field" prefix and ".name" suffix)
            // Example: "field20D.name" becomes "20D"
            var fieldName = fieldFullPart.Substring(5, fieldFullPart.Length - 5 - 5);

            // Add to dictionary - overwrite if duplicate keys exist (adjust if you need different behavior)
            mappings[fieldName] = description;
        }

        return mappings;
    }

    // Public method to get the formatted string for an input field
    public string GetFormattedDescription(string inputField)
    {
        if (string.IsNullOrWhiteSpace(inputField))
            throw new ArgumentNullException(nameof(inputField), "Input field cannot be null or empty.");

        var cleanedInput = inputField.Trim();
        if (_fieldDescriptions.TryGetValue(cleanedInput, out var description))
        {
            return $"{cleanedInput} - {description}";
        }
        else
        {
            return $"No description found for field: {cleanedInput}";
            // Alternatively, throw an exception if you want to enforce valid fields:
            // throw new KeyNotFoundException($"Field '{cleanedInput}' not found in mappings.");
        }
    }
}

Usage Example

Here's how you'd use this class in your program:

class Program
{
    static void Main()
    {
        try
        {
            // Replace with your actual TXT file path
            var mapper = new FieldDescriptionMapper(@"C:\path\to\your\field_mappings.txt");

            // Test with your sample inputs
            Console.WriteLine(mapper.GetFormattedDescription("20D"));
            // Output: 20D - Reference

            Console.WriteLine(mapper.GetFormattedDescription("20[101]"));
            // Output: 20[101] - Sender's Reference

            Console.WriteLine(mapper.GetFormattedDescription("20[102_STP]"));
            // Output: 20[102_STP] - File Reference
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Oops, something went wrong: {ex.Message}");
        }
    }
}

Key Notes

  • Case Insensitivity: The dictionary uses StringComparer.OrdinalIgnoreCase so inputs like "20d" or "20[101]" (lowercase) will still work. Remove this if you need strict case matching.
  • Duplicate Handling: If your TXT has duplicate field entries, the last one will overwrite the previous ones. Adjust the code if you need to handle duplicates differently (e.g., throw an error).
  • Error Handling: The code includes checks for missing files, empty inputs, and invalid line formats to make it more robust.

内容的提问来源于stack exchange,提问作者Сашко Мицевски

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:59:05