[英]What's the best way to set all values in a C# Dictionary<string,bool>?
[英]what is the best way to merge dictionary values based on given “key” string
我有以下字典:
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("ship", "I");
d.Add("shep", "V");
d.Add("ssed", "X");
d.Add("aspe", "L");
下面是输入文本行:string line =“ shep ship ship”;
我怎样才能最好的方式从上面的字典将上述行词(shep,ship和ship)转换为适当的罗马数字。 对于上面的行,它应显示为VII(shep shep ship)。
Dictionary<string, int> dCost = new Dictionary<string, int>();
dCost.Add("aspe aspe MaterialType1", 64);
dCost.Add("ssed ssed MaterialType2", 5880);
我想将dCost词典密钥aspe aspe aspe aspe MaterialType1
转换为从第一本词典开始的相应罗马数字,因此,在这两行上方均应转换为LL MaterialType1
和其他“ XX MaterialType2”。 也可以在新字典上获得结果,也可以只访问字典的第一个元素以获取/解析到罗马映射。
需要:目前,我一直在传递ROMAN值以转换其相关值,但是现在,我将按照上文在字典中提供的输入来映射ROMAN编号。 因此,我需要根据给定的输入获取适当的数字,并传递给API以将罗马文字转换为数字。
有人可以建议我将这些字典与其映射值合并的最佳方法吗,对于linq或任何方法都可以。
谢谢
确实还不清楚您要做什么,但是我怀疑这至少会有所帮助:
public static string ReplaceAll(string text,
Dictionary<string, string> replacements)
{
foreach (var pair in replacements)
{
text = text.Replace(pair.Key, pair.Value);
}
return text;
}
笔记:
如果我们假设成本键始终以单个词结尾(即MaterialType1 ),则键中的最后一个空格将要翻译的文本与材料类型名称分开。
例如:
“ aspe aspe MaterialType1”
要翻译此字符串,可以使用类似以下代码段的内容。
foreach(var cost in dCosts)
{
int lastSpaceIndex = cost.Key.LastIndexOf(" ");
string materialTypeName = cost.Key.Substring(lastSpaceIndex + 1)
.Trim();
string translatedKey = cost.Key.Substring(0, lastSpaceIndex);
foreach (var translation in d)
{
translatedKey = translatedKey.Replace(translation.Key, translation.Value)
.Trim();
}
translatedKey = translatedKey.Replace(" ", string.Empty);
Console.WriteLine("{0} {1} cost is {2}",
translatedKey,
materialTypeName,
cost.Value);
}
请以它为例。 您可以按以下方式实现“翻译的”字符串键。
foreach(var cost in dCosts)
{
string translatedKey = cost.Key;
foreach (var translation in d)
{
translatedKey = translatedKey.Replace(translation.Key, translation.Value)
.Trim();
}
Console.WriteLine("{0} cost is {1}", translatedKey, cost.Value);
}
正如@JonSkeet在他的答案中指出的那样,通过此代码段,您可以在“转换后的”值之间保留空格,因此,实际上并不是这种情况的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.