如何在列表中存储一个值及其字符串列表
本文关键字:列表 一个 字符串 存储 | 更新日期: 2023-09-27 18:10:35
我需要在List中存储一个值及其相应的字符串列表。像
Key Value
2 2,3
2 4,6
4 3,5,6
This should be in a list
这里我不能使用Dictionary,因为相同的键可能会重复。谁知道怎么用
使用Lookup
。这就像一个字典,只是它允许相同的键多次使用。
这里是文档。您必须在序列上使用.ToLookup
扩展方法来创建一个。
在你的情况下,似乎你需要一个ILookup<string, IList<string>>
(或int
而不是string
,我不知道你的数据)。
下面是生成查找的方法:
IEnumerable<KeyValuePair<string, IEnumerable<string>> myData = new[] {
new KeyValuePair<string, IEnumerable<string>>("2", new[] { "2", "3" }),
new KeyValuePair<string, IEnumerable<string>>("2", new[] { "4", "6" }),
new KeyValuePair<string, IEnumerable<string>>("4", new[] { "3", "5", "6" }),
};
var myLookup = myData.ToLookup(item => item.Key, item => item.Value.ToList());
如何区分两个'2'键?如果您不需要,那么使用int类型列表的列表的字典如何?键是键,值是包含所有重复键的列表的列表。
Dictionary<int, List<List<int>>> map;
这样的var map = new Dictionary<int, List<List<int>>>();
map[2] = new List<List<int>>();
map[2].Add(new List<int>(){ 2, 3});
map[2].Add(new List<int>(){ 4, 6});
map[4] = new List<List<int>>();
map[4].Add(new List<int>(){ 3, 5, 6});
foreach(var key in map.Keys)
{
foreach(var lists in map[key])
{
Console.WriteLine("Key: {0}", key);
foreach(var item in lists)
{
Console.Write(item);
}
Console.WriteLine();
}
}
如果您确实需要区分键,那么您需要为自定义类提供一个自定义hashCode(覆盖GetHashCode()函数),或者找到其他类型作为键来保证唯一性。
或者,保持简单,创建一个类。
public class ClassNameHere
{
public int Key { get; set; }
public List<string> Values { get; set; }
}
然后使用linq进行查找,等等
var someList = new List<ClassNameHere>();
//add some data
var lookupResult = someList.Where(x=>x.Key == 2);
如果你不喜欢(出于某些原因)使用Lookup
,而想使用List
类,你可以使用以下奇怪的结构:
var list = new List<Tuple<string, List<string>>> {
new Tuple<string, List<string>>("2", new List<string> {"2", "3"})
};
但是,我认为你应该三思而后行。当然,最好使用Lookup
。