C# 一个key 多个value
在C#中,可以使用Dictionary<TKey, List
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
// 添加key-value对
AddValue(dict, "key1", "value1");
AddValue(dict, "key1", "value2");
AddValue(dict, "key2", "value3");
// 获取key对应的所有value
List<string> valuesForKey1 = GetValues(dict, "key1");
List<string> valuesForKey2 = GetValues(dict, "key2");
// 输出结果
Console.WriteLine("Values for key1:");
foreach (string value in valuesForKey1)
{
Console.WriteLine(value);
}
Console.WriteLine("Values for key2:");
foreach (string value in valuesForKey2)
{
Console.WriteLine(value);
}
}
static void AddValue(Dictionary<string, List<string>> dict, string key, string value)
{
if (dict.ContainsKey(key))
{
dict[key].Add(value);
}
else
{
dict[key] = new List<string> { value };
}
}
static List<string> GetValues(Dictionary<string, List<string>> dict, string key)
{
if (dict.ContainsKey(key))
{
return dict[key];
}
else
{
return new List<string>();
}
}
}
以上代码中,我们使用Dictionary<string, List
原文地址: https://www.cveoy.top/t/topic/ihL6 著作权归作者所有。请勿转载和采集!