简体   繁体   English

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

[英]How can I add multiple params to a list in C#

how to add string to... 如何将字符串添加到...

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

is a list with ints.....I would like to add strings to this list for each record...trying... 是一个带有整数的列表.....我想为每个记录在此列表中添加字符串...尝试...

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

tells me unkown type of variable? 告诉我变量的未知类型?

List<T> is generic list of objects of type T . List<T>是类型T的对象的通用列表。

If you want to have pairs <int, sting> in this list, it should be not List<int, string> , but List<Some_Type<int, string>> . 如果要在此列表中具有对<int, sting> ,则它应该不是List<int, string> ,而是List<Some_Type<int, string>>

One of possible ways - is to use Tuple<T1, T2> as such a type. 一种可能的方法-将Tuple<T1, T2>用作此类类型。

Something like: 就像是:

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

Or you can use Dictionary<TKey, TValue> instead of list, but in this case your integer values should be unique. 或者,您可以使用Dictionary<TKey, TValue>代替list,但是在这种情况下,您的整数值应该是唯一的。

You can use Dictionary instead of List. 您可以使用字典而不是列表。 For example: 例如:

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

For more information: Dictionary Type on MSDN 有关更多信息: MSDN上的字典类型

You can just create a class: 您可以只创建一个类:

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

and then : 接着 :

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

You can also use HashTable or SortedList as another option to Dictionary. 您还可以使用HashTableSortedList作为Dictionary的另一个选项。 Both classes are in the System.Collections namespace 这两个类都在System.Collections命名空间中

Hashtable 哈希表

A Hashtable enables you to store key/value pair of any type of object. 哈希表使您可以存储任何类型的对象的键/值对。 The data is stored according to the hash code of the key and can be accessed by the key rather than the index. 数据根据密钥的哈希码存储,并且可以通过密钥而不是索引进行访问。 Example: 例:

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

SortedList SortedList

A SortedList is a collection that contains key/value pairs, but is different to the HashTable because it can be referenced by the index and because it is sorted. SortedList是一个包含键/值对的集合,但与HashTable不同,因为它可以被索引引用并且是已排序的。 Example: 例:

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

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

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