C# 筛选匹配指定字符串模式的LedgerEntity列表并修改对应字段
解决方案
前置修正
你给出的LedgerEntity模型中Accountlevel属性首字母为小写,与示例数据中的AccountLevel(大写L)字段名不一致,建议先统一修正属性名避免匹配失败:
public class LedgerEntity { public string AccountNumber{get;set;} public string AccountLevel{get;set;} // 修正首字母大写 public string AccountName{get;set;} }
实现逻辑
通过正则匹配符合GRP_*8112规则的记录,再通过字符串分割拼接完成AccountNumber的修改,两种实现方式可选:
方式1:生成新结果列表(不修改原数据)
需引入命名空间:
using System.Linq; using System.Text.RegularExpressions;
处理代码:
// 定义匹配规则:匹配包含GRP_+任意字符+8112的字符串 var regex = new Regex(@"GRP_.*?8112"); var matchedItems = items.Select(entity => { // 未匹配的记录直接返回原值 if (!regex.IsMatch(entity.AccountNumber)) { return new LedgerEntity { AccountNumber = entity.AccountNumber, AccountLevel = entity.AccountLevel, AccountName = entity.AccountName }; } // 第一步:移除AccountNumber中的GRP_ var newAccountNum = entity.AccountNumber.Replace("GRP_", string.Empty); // 第二步:按连字符拆分,给第三段末尾拼接70 var numParts = newAccountNum.Split('-'); if (numParts.Length >= 4) { numParts[2] += "70"; newAccountNum = string.Join("-", numParts); } // 返回修改后的记录 return new LedgerEntity { AccountNumber = newAccountNum, AccountLevel = "Individual", AccountName = entity.AccountName }; }).ToList();
方式2:直接修改原列表
var regex = new Regex(@"GRP_.*?8112"); foreach (var entity in items) { if (!regex.IsMatch(entity.AccountNumber)) continue; // 处理AccountNumber var newAccountNum = entity.AccountNumber.Replace("GRP_", string.Empty); var numParts = newAccountNum.Split('-'); if (numParts.Length >= 4) { numParts[2] += "70"; entity.AccountNumber = string.Join("-", numParts); } // 修改AccountLevel entity.AccountLevel = "Individual"; }
两种方式运行后得到的结果都和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Meena
相关产品推荐
相关产品推荐

