Create a list in C # with strings and int datatypes

How to create a list that contains both a string value and an int value? Can anyone help me. Is it possible to create a list with different data types?

+4
source share
3 answers

You can 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 can 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 the string or integer is unique to the set, you can use:

 Dictionary<int, string> or Dictionary<string, int> 
+9
source

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

+10
source

You can make a list containing any object of interest to you. 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>(); 
+2
source

Source: https://habr.com/ru/post/1380717/


All Articles