如何在c#中向列表添加多个参数

本文关键字:添加 参数 列表 | 更新日期: 2023-09-27 18:15:53

如何添加字符串到…

List<int> mapIds = new List<int>();
mapIds.Add(36);
mapIds.Add(37);
mapIds.Add(39);

是一个int型列表.....我想为每个记录添加字符串到这个列表中…尝试…

List<int, string> mapIds = new List<int, string>();
mapIds.Add(36, "hi");
mapIds.Add(37, "how");
mapIds.Add(39, "now");

告诉我未知类型的变量?

如何在c#中向列表添加多个参数

List<T>T类型对象的泛型列表。

如果你想在这个列表中有对<int, sting>,它不应该是List<int, string>,而是List<Some_Type<int, string>>

一种可能的方法是使用Tuple<T1, T2>作为这样的类型。

类似:

var mapIds = new List<Tuple<int, string>>();
mapIds.Add(new Tuple<int, string>("36", "hi"));

或者您可以使用Dictionary<TKey, TValue>而不是list,但在这种情况下,您的整数值应该是唯一的

您可以使用Dictionary代替List。例如:

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(36, "hi");

查看更多信息:MSDN上的字典类型

你可以直接创建一个类:

class Custom
{
   public int myInt {get;set;}
   public string myString {get;set}
}

然后:

List<Custom> mapIds = new List<Custom>();
Custom c = new Custom();
c.myInt = 36;
c.myString="hi";
mapIds.Add(c);    
....
...

您也可以使用HashTable或SortedList作为字典的另一个选项。这两个类都在系统中。集合名称空间

Hashtable

Hashtable可以存储任何类型对象的键/值对。数据根据键的哈希码存储,可以通过键而不是索引访问。例子:

Hashtable myHashtable = new Hashtable(); 
myHashtable.Add(1, "one"); 
myHashtable.Add(2, "two"); 
myHashtable.Add(3, "three");

SortedList

SortedList是一个包含键/值对的集合,但与HashTable不同,因为它可以被索引引用,并且因为它是排序的。例子:

SortedList sortedList = new System.Collections.SortedList();
sortedList.Add(3, "Third");
sortedList.Add(1, "First");
sortedList.Add(2, "Second");