Reputation: 163
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?
Upvotes: 6
Views: 45271
Reputation: 5325
You can make have the list contain any object you like. Why don't you create a 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<CustomObject> CustomObject = new List<CustomObject>();
Upvotes: 3
Reputation: 1443
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>
Upvotes: 12
Reputation: 1062770
List<T>
is homogeneous. The only real way to do that is to use List<object>
which will store any value.
Upvotes: 10