我尝试从字典中检索特定的对,并将这对转换为字符串,如下所示:
Dictionary<string, string> testDictionary= new Dictionary<string, string>();
testDictionary.Add("3123", "1");
testDictionary.Add("3523", "2");
testDictionary.Add("5532", "1");
string memberId="5532";
string finalSelectedValue = testDictionary.Where(x => x.Key == memberId).Select(y => y.Key + "_" + y.Value).ToString();
Console.WriteLine(finalSelectedValue);
但是,我不知道如何实现在字典中组合这对特定对的键和值的最后一步。
预期结果是:“5532_1”
最佳答案
这里不需要 LINQ,因为字典不能有重复的键。您真正需要的 - 只需按键输入并格式化其值(字典对于此任务非常有效):
string memberId = "5532";
string value;
if (testDictionary.TryGetValue(memberId, out value))
{
string finalSelectedValue = String.Format("{0}_{1}", memberId, value);
}
else
{
// member not found
}
性能较低,但单行:
string finalSelectedValue = testDictionary.ContainsKey(memberId) ?
$"{memberId}_{testDictionary[memberId]}" : null; // C# 6 string formatting
为什么您的方法不起作用?您正在计算所有字典条目以查找字典中是否存在某些键(这是一个很大的矫枉过正)。 Where
运算符将返回空集合或包含单个条目的集合(因为字典不能有重复的键)。之后,您将过滤结果投影到字符串集合(同样是一个或零个项目)。然后您将集合转换为字符串 - 但只会返回集合的类型名称 IEnumerable<string>
.要修复您的代码,您需要替换最后一个 ToString()
与 FirstOrDefault()
你会得到单一格式的字符串或 null
如果找不到条目。但是.. 见上:)
关于c# - 如何从字典中检索键/值,并将它们组合成一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33247961/