这个答案是根据原始海报的要求从评论中“提升”的。
如果保持插入顺序对您很重要,您可能只想使用 a List<>,其元素以某种方式是字符串对。两种解决方案是很自然的:
var colunas = new List<KeyValuePair<string, string>>();
colunas.Add(new KeyValuePair<string, string>("Nome", "Nome"));
colunas.Add(new KeyValuePair<string, string>("Departamento", "Departamento"));
colunas.Add(new KeyValuePair<string, string>("Cargo", "Cargo"));
或者:
var colunas = new List<Tuple<string, string>>();
colunas.Add(Tuple.Create("Nome", "Nome"));
colunas.Add(Tuple.Create("Departamento", "Departamento"));
colunas.Add(Tuple.Create("Cargo", "Cargo"));
和之间存在技术差异KeyValuePair<,>,Tuple<,>因为前者是struct(值类型)而后者是class(引用类型),但由于两者KeyValuePair<,>都是Tuple<,>不可变类型,这可能并不重要。然后决定属性名称Key/Value或Item1/Item2是否最适合您的使用。
请注意,如果您使用此解决方案,您将无法获得哈希表提供的好处。您无法快速查找密钥。并且不能保证List<>不能有许多具有相同“键”字符串(该对的第一个组件)的条目。那个字符串甚至可以是null.
List<>毕竟,如果您想colunas.Sort();对. 当然,如果您希望始终按键对集合进行排序,按照另一个答案的建议使用。Tuple<,>KeyValuePair<,>SortedDictionary<string, string>