c# - 如何从字典中检索键/值,并将它们组合成一个字符串

标签 c# dictionary

我尝试从字典中检索特定的对,并将这对转换为字符串,如下所示:

        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/

相关文章:

c# - 如何更改 WPF 中的按钮样式,由 bool 值触发?

c# - 检查类型是否可转换/子类

c# - 如何找到特定行的行号?

c# - 在ASP.NET C#项目中实现异常处理

c# - 将字节数组从 Unity C# 传递到 C++ 插件

c# - 使用 JSON 字符串填充 ASP.Net DropDownList

python - 优化比较次数

ios - 无法识别的选择器 [MKPointAnnotation 索引]

python - 创建一个包含先前单词词典中所有字母转换的词典?

PHP将由字典项组成的数组保存到MySQL表中