因此,我有一个字典,其中的键是地址缩写的缩写版本(这是我在该词典中的值)。我需要在字典中搜索字符串是否包含值,然后用字典中的键值替换字符串中匹配的值。例如:
Dictionary<string, string> addresses = new Dictionary<string, string>(){"BLVD","BOULEVARD"};
var address = "405 DAVIS BOULEVARD";
因此,在上面的示例中,我想找到“ BOULEVARD”作为匹配项,然后将其替换为“ BLVD”。因此,新地址将为“ 405 DAVIS BLVD”。到目前为止,下面的代码是我所拥有的,但是我不确定如何使用适当的键值完成替换部分。任何提示将不胜感激,谢谢!
foreach(var value in addresses.Values)
{
if(address.ToUpper().Contains(value))
{
//this is where i get stuck with how to replace with the appropriate key of the dictionary
}
}
最简单的解决方案是反转您的关键和价值,Dictionary<string, string> addresses = new Dictionary<string, string>(){"BOULEVARD","BLVD"};
然后,您只需查找密钥即可替换:address = address.Replace(key, addresses[key]);
我们可以先找到键值对,然后使用替换:
Dictionary<string, string> addresses = new Dictionary<string, string>() { { "BLVD", "BOULEVARD" } };
var address = "405 DAVIS BOULEVARD";
KeyValuePair<string,string> keyValue =
addresses.FirstOrDefault((x) => address.ToUpper().Contains(x.Value));
if(keyValue.Value != null)
{
address = address.ToUpper().Replace(keyValue.Value, keyValue.Key);
}
注意:请为扩展方法using System.Linq;
添加FirstOrDefault
(如果不存在)>>