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

C# 基于部门、月份双参数自动生成递增序列号的实现方案

流水号实现方案

核心逻辑

流水号按「部门编码+年月」组合维度独立递增:同一个部门同一个自然月内,流水号从01开始累加;切换部门或者到新的月份后,流水号重置为01重新计数。
你需要提前准备持久化存储介质来记录每组「部门编码+年月」对应的当前最大流水号,单用户本地应用可以用本地文本/INI/JSON文件存储,多用户联网系统推荐用数据库/Redis存储。

C# 代码示例(本地JSON存储适配你的现有代码)

.NET Core 3.0+自带System.Text.Json可直接使用,低版本可替换为Newtonsoft.Json,示例代码如下:

using System.IO;
using System.Text.Json;

// 1. 拼接分组维度key:部门编码+两位年月
string groupKey = textBox2.Text.Trim() + dtim.ToString("yyMM");
string configPath = "serial_number_record.json";
Dictionary<string, int> serialRecord;

// 2. 读取历史流水号记录
if (File.Exists(configPath))
{
    string json = File.ReadAllText(configPath);
    serialRecord = JsonSerializer.Deserialize<Dictionary<string, int>>(json) ?? new Dictionary<string, int>();
}
else
{
    serialRecord = new Dictionary<string, int>();
}

// 3. 计算当前流水号,不足两位自动补0
int currentSerial = serialRecord.ContainsKey(groupKey) ? serialRecord[groupKey] + 1 : 1;
string serialNumber = "_" + currentSerial.ToString("00");

// 4. 更新记录持久化存储
serialRecord[groupKey] = currentSerial;
File.WriteAllText(configPath, JsonSerializer.Serialize(serialRecord));

// 5. 最终赋值到文本框
textBox1.Text = groupKey + serialNumber;

注意事项

  • 多用户并发场景不要用本地文件存储,需改用数据库存储,操作时增加事务/行锁逻辑,避免多个请求拿到重复的流水号
  • 如果要求流水号严格连续无跳号,需要等对应业务数据提交成功后再更新流水号存储,避免生成流水号后业务取消造成号段浪费

内容的提问来源于stack exchange,提问作者petule.08

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:45:04