[英]Get the list of items matching a specific pattern of string
我有一個C#
模型LedgerEntity
。
public class LedgerEntity
{
public string AccountNumber{get;set;}
public string Accountlevel{get;set;}
public string AccountName{get;set;}
}
我還有一個該模型類的項目列表,如下所示
List<LedgerEntity> items=new List<LedgerEntity>();
items=[
{"AccountNumber":"07-01-GRP_10095-81120000","AccountLevel":"Group","AccountName":"JPM"},
{"AccountNumber":"G3-80-GRP_10895-8112SLC0","AccountLevel":"Group","AccountName":"CIT"},
{"AccountNumber":"1C-MULTI-2851170-MULTI_8113xxxx","AccountLevel":"Group","AccountName":"BON"},
{"AccountNumber":"07-MULTI-MULTI_NONCORE-MULTI","AccountLevel":"Group","AccountName":"CUK"}}
]
我的要求是這樣的。 我需要獲取所有包含的記錄
"GRP_*8112(* can have any value like 10095- or 10895- etc...)" in `AccountNumber. Then remove "GRP_" from the record and add "70" in front of the 3rd hyphen.
Example: 07-01-GRP_10095-81120000 --> 07-01-1009570-81120000
還將匹配記錄的Accountlevel
從Group
為Individual
。
我的預期輸出是這樣的。
matchedItems=[
{"AccountNumber":"07-01-1009570-81120000","AccountLevel":"Individual","AccountName":"JPM"},
{"AccountNumber":"G3-80-1089570-8112SLC0","AccountLevel":"Individual","AccountName":"CIT"},
{"AccountNumber":"1C-MULTI-2851170-MULTI_8113xxxx","AccountLevel":"Group","AccountName":"BON"},
{"AccountNumber":"07-MULTI-MULTI_NONCORE-MULTI","AccountLevel":"Group","AccountName":"CUK"}}
]
請幫我解決這個問題。
你的問題可以用Regex用這樣的表達式來解決,例如:
(10(8|0)95)
您可以使用以下代碼:
items.Where(item => Regex.IsMatch(item.AccountNumber, @"10(8|0)95)"))
嘗試這個
foreach (var item in items)
{
var grpIndex = item.AccountNumber.IndexOf("GRP_");
if (grpIndex >= 0)
{
var numberIndex = item.AccountNumber.Substring(grpIndex + 4).IndexOf("8112");
if (numberIndex >= 0)
{
item.AccountNumber = item.AccountNumber.Replace("GRP_", "");
item.Accountlevel = "Individual";
var i = 0;
var counter = 0;
foreach (var ch in item.AccountNumber)
{
if (ch == '-') counter++;
if (counter == 3) break;
i++;
}
if (counter == 3) item.AccountNumber = item.AccountNumber.Insert(i, "70");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.