我是一名LINQ新手,从事涉及国际邮政地址的GIS项目。我的一个设计问题涉及按国家/地区将键/值对格式的分解地址数据动态转换为多行邮政地址格式。根据国家和地址行定义的一组规则,每条记录都需要根据Country
字段值进行自我组合:
Dictionary<string, string> addressOne = new Dictionary<string,string>() {
{ "StreetName", "Stradă Măguricea" },
{ "HouseNumber", "1" },
{ "ApartmentLabel", "Ap" },
{ "ApartmentNumber", "17" },
{ "PostalCode", "014231" },
{ "City", "BUCUREŞTI" },
{ "Country", "Romania" }
};
Dictionary<string, string> addressTwo = new Dictionary<string,string>() {
{ "StreetName", "PORTAGE" },
{ "StreetSuffix", "AVE" },
{ "HouseNumber", "811" },
{ "City", "WINNIPEG" },
{ "StateProvince", "MB" },
{ "PostalCode", "R3B 2A8" },
{ "Country", "CANADA" }
};
//Example Concatenation Rules (these are approximations)...
//Romania: AddressLine1 = "{StreetName}[ {StreetSuffix}] {HouseNumber}[, {ApartmentLabel} {ApartmentNumber}"
// AddressLine2 = "{PostalCode} {City}"
// AddressLine3 = "{Country}"
//Canada: AddressLine1 = "{HouseNumber} {StreetName}[ {StreetSuffix}]"
// AddressLine2 = "[{ApartmentLabel} {ApartmentNumber}]"
// AddressLine3 = "{City} {StateProvince} {PostalCode}"
// AddressLine4 = "{Country}"
我目前正计划一个由Country
和AddressLine
调用的函数表,每个Func
返回一个由相应的连接规则格式化的复合字段。我总是可以使用传统的StringBuildler
逻辑来实现这些规则函数,但这对于LINQ查询来说似乎已经成熟。
我的大部分搜索都是通常comma aggregation scenarios;这更像是一个有选择性的条件模式匹配问题(我已经闻到了正则表达式)。这是LINQ的一个很好的用例,还是我应该坚持老派的分支字符串操作?
感谢阅读!
答案 0 :(得分:1)
我喜欢Linq和词典:
public static IEnumerable<string> InjectFields(IDictionary<string, string> address)
{
string country = address["Country"];
return formatStrings[country]
.Select(s => address.Aggregate(s, (acc, pair) => acc.Replace("{"+pair.Key+"}", pair.Value)))
.ToArray();
}
private static Dictionary<string, IEnumerable<string>> formatStrings =
new Dictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase)
{
{ "Romania", new[] {
"{StreetName}[ {StreetSuffix}] {HouseNumber}[, {ApartmentLabel} {ApartmentNumber}",
"{PostalCode} {City}",
"{Country}",
} },
{ "Canada", new[] {
"{HouseNumber} {StreetName}[ {StreetSuffix}]",
"[{ApartmentLabel} {ApartmentNumber}]",
"{City} {StateProvince} {PostalCode}",
"{Country}"
} },
};