0

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?

1
  • what is the list class are you using??? O.O . as far as i know the list class signature is List<T> not List<T,X>. if you want to have some key value stuff you should use Dictionary<TKey, TValue> class Commented Oct 2, 2015 at 12:00

4 Answers 4

4

List<T> is generic list of objects of type 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>>.

One of possible ways - is to use Tuple<T1, T2> as such a type.

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

This should be a comment, not an answer.
2

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);    
....
...

Comments

0

You can also use HashTable or SortedList as another option to Dictionary. Both classes are in the System.Collections namespace

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

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. Example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.