简体   繁体   English

在.net 2.0中存储非唯一对?

[英]Store non-unique pairs in .net 2.0?

I have to store a pair of strings that are non-unique, so I could have something like: 我必须存储一对非唯一的字符串,所以我可能有类似的东西:

"A", "B" "A","C" "A", "B" "A","C"

I can't use a Dictionary or HashTable because I don't have a unique key. 我不能使用Dictionary或HashTable,因为我没有唯一的密钥。 I thought about a couple options: 我想过几个选择:

List<List<string>,List<string>> = new List<List<string>,List<string>>(); //Too long?

Create a class or struct (what is better?) to hold my pairs and then store that in list, so 创建一个类或结构(什么更好?)来保存我的对,然后将其存储在列表中,所以

class pairs
{

}

List<pairs> values = new List<pairs>();

I also just need to be able to enumerate through the pairs, so I don't need care about querying, sorting, comparing. 我还需要能够通过对进行枚举,所以我不需要关心查询,排序和比较。 Because of this, is it best to use the least specific type, such as Enumerable? 因此,最好使用最不具体的类型,例如Enumerable?

You should be able to use a List<KeyValuePair<string, string>> . 您应该能够使用List<KeyValuePair<string, string>>

KeyValuePair<TKey, TValue> structs by themselves don't require unique keys, even if you collect them in a single list. KeyValuePair<TKey, TValue>结构本身不需要唯一的密钥,即使您将它们收集在一个列表中也是如此。

If you think KVPs don't ring well semantically with what you want, just go with a custom type. 如果您认为KVP在语义上不能满足您的需求,那么只需使用自定义类型即可。 It shouldn't matter whether your custom type is a class or struct. 您的自定义类型是类还是结构无关紧要。

What about just a List<string[]> ? 怎么样只是一个List<string[]>

var list = new List<string[]>();

list.Add(new [] { "A", "B"});

foreach(var pair in list)
{
   Console.WriteLine(pair[0] + pair[1]);
}

可以使用List<KeyValuePair<string,string>> ,但是为了避免键的语义(因为你说它不是唯一的),我会使用List<Tuple<string,string>> ,这实际上是相同但具有不同的语义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM