Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list in C# with string and int datatypes

Tags:

c#

How can I create a list which holds both string value and int value? Can anyone help me please.Is it possible to create a list with different datatypes?

like image 841
michelle Avatar asked Nov 11 '11 06:11

michelle


People also ask

What is a list in C programming?

What is Linked List in C? A Linked List is a linear data structure. Every linked list has two parts, the data section and the address section that holds the address of the next element in the list, which is called a node.

Is array a list in C?

Array of Linked Lists in C/C++ An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array.

How do you create an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.


2 Answers

You could use:

var myList = new List<KeyValuePair<int, string>>();
myList.Add(new KeyValuePair<int, string>(1, "One");

foreach (var item in myList)
{
    int i = item.Key;
    string s = item.Value;
}

or if you are .NET Framework 4 you could use:

var myList = new List<Tuple<int, string>>();
myList.Add(Tuple.Create(1, "One"));

foreach (var item in myList)
{
    int i = item.Item1;
    string s = item.Item2;
}

If either the string or integer is going to be unique to the set, you could use:

Dictionary<int, string> or Dictionary<string, int>
like image 151
Raghu Avatar answered Oct 23 '22 04:10

Raghu


List<T> is homogeneous. The only real way to do that is to use List<object> which will store any value.

like image 10
Marc Gravell Avatar answered Oct 23 '22 04:10

Marc Gravell