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?
-
for what purpose? do you mean a key/value pair, or actually storing both types side by side in the list?nathan gonzalez– nathan gonzalez2011-11-11 07:00:41 +00:00Commented Nov 11, 2011 at 7:00
-
That would be a list of objects List<object> or an ArrayList.....Polity– Polity2011-11-11 07:02:36 +00:00Commented Nov 11, 2011 at 7:02
-
@nathan it is for actually storing both datatype valuesmichelle– michelle2011-11-11 07:04:27 +00:00Commented 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?Jon Skeet– Jon Skeet2011-11-11 07:07:29 +00:00Commented Nov 11, 2011 at 7:07
Add a comment
|
3 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>
Comments
List<T> is homogeneous. The only real way to do that is to use List<object> which will store any value.
1 Comment
Marc Gravell
@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.
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>();