如何对Dictionary<string, List<int>>应用string.Join实现指定格式输出?
解决Dictionary<string, List>格式化问题
你的代码输出类型名,大概率是实际编写时误将字典对象写成了字典的Keys集合(比如iformation.Keys),导致Linq查询的是键集合而非键值对集合。另外你的格式细节也和预期有出入,以下是修正后的实现:
正确代码
// 假设字典变量名为information(你原代码里的iformation可能是拼写错误) string result = string.Join(",", information.OrderBy(x => x.Key) .Select(x => $"{x.Key}:{string.Join(",", x.Value)}"));
关键修正点
- 外层
string.Join的分隔符用","而非", ",匹配你预期的无空格格式 - 键和值列表之间去掉多余空格,用
{x.Key}:替代x.Key + ": " - 确保Linq查询的是字典的键值对集合(
information而非information.Keys),这样x才能同时获取到Key和Value属性
示例验证
如果你的字典是:
Dictionary<string, List<int>> information = new Dictionary<string, List<int>> { {"abc2", new List<int> {1, 3, 8}}, {"abc1", new List<int> {1, 2, 3, 4}}, {"abc3", new List<int> {3, 1, 7}} };
执行修正后的代码会得到预期结果:abc1:1,2,3,4,abc2:1,3,8,abc3:3,1,7
内容的提问来源于stack exchange,提问作者user3085082
相关产品推荐
相关产品推荐

