6

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?

4
  • for what purpose? do you mean a key/value pair, or actually storing both types side by side in the list? Commented Nov 11, 2011 at 7:00
  • That would be a list of objects List<object> or an ArrayList..... Commented Nov 11, 2011 at 7:02
  • @nathan it is for actually storing both datatype values Commented Nov 11, 2011 at 7:04
  • @michelle: That doesn't really answer nathan's question very clearly. Both for the same element or both for different elements? Commented Nov 11, 2011 at 7:07

3 Answers 3

12

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>
Sign up to request clarification or add additional context in comments.

Comments

10

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

1 Comment

@AteşGÜRAL that depends entirely on the wider scenario. In many cases, no. But if your requirement is to store both things - it isn't bad as such. Simply : you need to be a little careful.
3

You can make have the list contain any object you like. Why don't you create a custom object

Custom Object

public class CustomObject
{
    public string StringValue { get; set; }
    public int IntValue { get; set; }

    public CustomObject()
    {
    }

    public CustomObject(string stringValue, int intValue)
    {
        StringValue = stringValue;
        IntValue = intValue;
    }
}

List Creation

List<CustomObject> CustomObject = new List<CustomObject>();

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.