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

C#实现文本文件数据与Firebird数据库记录比对取较大值咨询

实现代码(可直接替换Main方法中//READ FROM TXT之后的逻辑)

首先优化原zwr方法的空引用问题,再新增比对逻辑:

//RETURN STANDYSP FUNCTION 优化空值处理
double zwr(string myIndex)
{
    var item = lista1.FirstOrDefault(x => x.index == myIndex);
    // 若数据库中不存在该索引,默认返回极小值优先取文本值,可根据业务需求调整规则
    return item == null ? double.MinValue : item.standysp;
}

// 初始化比对结果列表
List<WynikPorownania> wynikList = new List<WynikPorownania>();

//READ FROM TXT 逐行解析,无需同时调用ReadAllText和StreamReader
string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
// 读取所有行并跳过空行
var textLines = File.ReadAllLines(path).Where(line => !string.IsNullOrWhiteSpace(line));

foreach (var line in textLines)
{
    // 拆分索引和对应数值,跳过格式错误的行
    var parts = line.Split('=');
    if (parts.Length != 2) continue;
    
    string txtIndex = parts[0].Trim();
    if (!int.TryParse(parts[1].Trim(), out int txtValue)) continue;

    // 获取数据库中对应索引的可用性值
    double dbValue = zwr(txtIndex);

    // 取最大值存入结果列表
    int finalValue = (int)Math.Max(txtValue, dbValue);
    wynikList.Add(new WynikPorownania
    {
        Indeks = txtIndex,
        Ilosc = finalValue
    });
}

// 可选:测试输出结果验证逻辑正确性
foreach (var res in wynikList)
{
    Console.WriteLine($"索引:{res.Indeks},最终值:{res.Ilosc}");
}

myConnection.Close();

逻辑说明

  • 优化后的zwr方法增加了空值判断,避免数据库中不存在对应索引时触发空引用异常,不存在时的默认返回规则可根据业务需求调整
  • 文本读取改用File.ReadAllLines逐行处理,自动过滤空行和格式不符合索引=值规则的无效行
  • 比对时直接调用Math.Max取两个值的最大值,转换为int类型存入WynikPorownania实例的Ilosc字段
  • 最终比对结果全部存储在wynikList列表中,可根据后续需求做持久化、导出等操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:54:03