方法一
C#
Dictionary<string, string> StateCodesDic = new Dictionary<string, string>();
StateCodesDic.Add("Johor", "01");
StateCodesDic.Add("Kedah", "02");
StateCodesDic.Add("Kelantan", "03");
StateCodesDic.Add("Melaka", "04");
StateCodesDic.Add("Negeri Sembilan", "05");
StateCodesDic.Add("Pahang", "06");
StateCodesDic.Add("Pulau Pinang", "07");
StateCodesDic.Add("Perak", "08");
StateCodesDic.Add("Perlis", "09");
StateCodesDic.Add("Selangor", "10");
StateCodesDic.Add("Terengganu", "11");
StateCodesDic.Add("Sabah", "12");
StateCodesDic.Add("Sarawak", "13");
StateCodesDic.Add("Wilayah Persekutuan Kuala Lumpur", "14");
StateCodesDic.Add("Wilayah Persekutuan Labuan", "15");
StateCodesDic.Add("Wilayah Persekutuan Putrajaya", "16");
StateCodesDic.Add("Not Applicable", "17");
方法二
你的代码逻辑是要根据 tempStateID = "KUALA" 匹配到 "Wilayah Persekutuan Kuala Lumpur" 并返回对应的编码 "14"。
问题分析
-
当前代码的问题:
- 你使用了
lowerCaseDictionary,但"KUALA"并不直接匹配"wilayah persekutuan kuala lumpur"(全小写)。 - 你的
FindModel使用了Contains查询,但"kuala"只是部分匹配,需要确保查询方式正确。
- 你使用了
-
优化方案:
- 直接遍历
StateCodesDic,检查Key是否包含tempStateID(不区分大小写)。 - 使用
StringComparison.OrdinalIgnoreCase进行不区分大小写的比较。
- 直接遍历
修改后的代码
csharp
public ActionResult TestDemo()
{
Dictionary<string, string> StateCodesDic = new Dictionary<string, string>
{
{ "Johor", "01" },
{ "Kedah", "02" },
{ "Kelantan", "03" },
{ "Melaka", "04" },
{ "Negeri Sembilan", "05" },
{ "Pahang", "06" },
{ "Pulau Pinang", "07" },
{ "Perak", "08" },
{ "Perlis", "09" },
{ "Selangor", "10" },
{ "Terengganu", "11" },
{ "Sabah", "12" },
{ "Sarawak", "13" },
{ "Wilayah Persekutuan Kuala Lumpur", "14" },
{ "Wilayah Persekutuan Labuan", "15" },
{ "Wilayah Persekutuan Putrajaya", "16" },
{ "Not Applicable", "17" }
};
string tempStateID = "KUALA";
string msg = "17"; // 默认值,未匹配时返回 "17"
dynamic FindModel = new { Key = "", Value = "" };
// 遍历字典,查找 Key 包含 "KUALA"(不区分大小写)的项
foreach (var item in StateCodesDic)
{
if (item.Key.IndexOf(tempStateID, StringComparison.OrdinalIgnoreCase) >= 0)
{
FindModel = new { Key = item.Key, Value = item.Value };
msg = item.Value;
break; // 找到第一个匹配项后退出循环
}
}
return Json(new
{
Data = FindModel,
keyCode = msg
});
}
关键优化点
- 直接遍历
StateCodesDic:- 不需要额外转换大小写,直接使用
IndexOf+StringComparison.OrdinalIgnoreCase进行模糊匹配。
- 不需要额外转换大小写,直接使用
- 更高效的匹配方式 :
item.Key.IndexOf(tempStateID, StringComparison.OrdinalIgnoreCase) >= 0检查Key是否包含"KUALA"(不区分大小写)。
- 默认值处理 :
- 如果没有匹配项,默认返回
"17"(对应"Not Applicable")。
- 如果没有匹配项,默认返回
测试结果
-
当
tempStateID = "KUALA"时,会匹配到"Wilayah Persekutuan Kuala Lumpur",返回:json{ "Data": { "Key": "Wilayah Persekutuan Kuala Lumpur", "Value": "14" }, "keyCode": "14" } -
如果
tempStateID = "JOHOR",则返回:json{ "Data": { "Key": "Johor", "Value": "01" }, "keyCode": "01" } -
如果
tempStateID = "XXX"(无匹配),则返回:json{ "Data": { "Key": "", "Value": "" }, "keyCode": "17" }
这样就能正确获取到 "14" 这个编码了! 🚀