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

如何实现文本文件中条目与对应数值的关联及赋值操作?

需求与问题描述

现有一段C#基础代码,可将内容写入test.txt并在退出时保存,重复运行程序调用ReadLine()能追加内容,但无法识别文件中的不同条目。原代码存在变量名错误(content应为items),代码如下:

static void Main(string[] args)
{
    if (File.Exists("test.txt"))
    {
        string items = File.ReadAllText("test.txt");
        Console.WriteLine("Current inventory stock:");
        Console.WriteLine(content); // 原代码变量名错误:content应为items
    }
    Console.WriteLine("Please enter a new tool into the inventory: ");
    string newItems = Console.ReadLine();
    while (newItems != "exit")
    {
        File.AppendAllText("test.txt", newItems + Environment.NewLine);
        newItems = Console.ReadLine();
    }
}

文本文件格式为每行一个条目,逗号分隔:

ItemOne, ItemInfo, 2
ItemTwo, ItemInfo, 6
ItemThree, ItemInfo, 4
ItemFour, ItemInfo, 1
ItemFive, ItemInfo, 7

需要实现整数数值与对应条目关联(比如2仅属于ItemOne),并能对这些关联条目进行管理。

实现条目与数值关联的步骤

1. 定义实体类封装条目信息

创建类来存储每个条目的属性,让条目与数值的关联更清晰:

public class InventoryItem
{
    public string Name { get; set; }
    public string Info { get; set; }
    public int Quantity { get; set; }
}

2. 读取并解析文本文件

将文件每行内容解析为InventoryItem对象,存入集合统一管理:

List<InventoryItem> inventory = new List<InventoryItem>();

if (File.Exists("test.txt"))
{
    string[] lines = File.ReadAllLines("test.txt");
    foreach (string line in lines)
    {
        string[] parts = line.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length == 3 && int.TryParse(parts[2], out int quantity))
        {
            inventory.Add(new InventoryItem
            {
                Name = parts[0],
                Info = parts[1],
                Quantity = quantity
            });
        }
    }
}

3. 管理条目(查询、修改、新增)

通过集合操作实现条目与数值的关联管理:

  • 查询指定条目:
    var targetItem = inventory.FirstOrDefault(i => i.Name == "ItemOne");
    if (targetItem != null)
    {
        Console.WriteLine($"{targetItem.Name} 的数量是: {targetItem.Quantity}");
    }
    
  • 修改条目数量:
    if (targetItem != null)
    {
        targetItem.Quantity += 3; // 数量增加3
    }
    
  • 新增条目(含格式校验):
    Console.WriteLine("请输入新条目(格式:名称, 信息, 数量):");
    string input = Console.ReadLine();
    while (input != "exit")
    {
        string[] parts = input.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length == 3 && int.TryParse(parts[2], out int quantity))
        {
            inventory.Add(new InventoryItem
            {
                Name = parts[0],
                Info = parts[1],
                Quantity = quantity
            });
        }
        else
        {
            Console.WriteLine("输入格式错误,请重新输入!");
        }
        input = Console.ReadLine();
    }
    

4. 将集合保存回文本文件

退出前把集合中的对象重新格式化为文本行,覆盖写入文件:

List<string> outputLines = new List<string>();
foreach (var item in inventory)
{
    outputLines.Add($"{item.Name}, {item.Info}, {item.Quantity}");
}
File.WriteAllLines("test.txt", outputLines);

完整可运行示例代码

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

public class InventoryItem
{
    public string Name { get; set; }
    public string Info { get; set; }
    public int Quantity { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<InventoryItem> inventory = LoadInventory();

        // 显示当前库存
        Console.WriteLine("当前库存:");
        foreach (var item in inventory)
        {
            Console.WriteLine($"{item.Name}, {item.Info}, {item.Quantity}");
        }

        // 新增或更新条目
        Console.WriteLine("\n请输入新条目(格式:名称, 信息, 数量),输入exit退出:");
        string input = Console.ReadLine();
        while (input != "exit")
        {
            string[] parts = input.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
            if (parts.Length == 3 && int.TryParse(parts[2], out int quantity))
            {
                var existingItem = inventory.FirstOrDefault(i => i.Name == parts[0]);
                if (existingItem != null)
                {
                    existingItem.Quantity = quantity;
                    Console.WriteLine($"已更新 {parts[0]} 的数量为 {quantity}");
                }
                else
                {
                    inventory.Add(new InventoryItem
                    {
                        Name = parts[0],
                        Info = parts[1],
                        Quantity = quantity
                    });
                    Console.WriteLine($"已新增条目:{parts[0]}");
                }
            }
            else
            {
                Console.WriteLine("输入格式错误,请按照「名称, 信息, 数量」的格式输入!");
            }
            input = Console.ReadLine();
        }

        // 保存库存到文件
        SaveInventory(inventory);
        Console.WriteLine("库存已保存,程序退出。");
    }

    static List<InventoryItem> LoadInventory()
    {
        List<InventoryItem> inventory = new List<InventoryItem>();
        if (File.Exists("test.txt"))
        {
            string[] lines = File.ReadAllLines("test.txt");
            foreach (string line in lines)
            {
                string[] parts = line.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 3 && int.TryParse(parts[2], out int quantity))
                {
                    inventory.Add(new InventoryItem
                    {
                        Name = parts[0],
                        Info = parts[1],
                        Quantity = quantity
                    });
                }
            }
        }
        return inventory;
    }

    static void SaveInventory(List<InventoryItem> inventory)
    {
        List<string> outputLines = new List<string>();
        foreach (var item in inventory)
        {
            outputLines.Add($"{item.Name}, {item.Info}, {item.Quantity}");
        }
        File.WriteAllLines("test.txt", outputLines);
    }
}

学习方向建议

  • 掌握C#类与对象的概念,这是封装条目信息的核心基础。
  • 熟悉List<T>集合的常用操作(添加、查询、修改),用于批量管理库存条目。
  • 学习File.ReadAllLines和File.WriteAllLines的用法,掌握逐行读写文本的逻辑。
  • 理解字符串分割Split和类型安全转换int.TryParse的用法,处理文本解析时的异常情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:00:18