How to make a List
with 3 columns in C#?
Each columns must have a different type
.
Now I have tried this.
List<int> list1 = new List<int>();
List<decimal> list2 = new List<decimal>();
List<string> list3 = new List<string>();
How can I combine this in one List
?
In order to read it in one for
, and access it.
You can create a List
of tuples for that, using list initializer
var list = new List<(int item, string data, decimal value)>
{
(1, "test", 1.2m),
(2, "test", 3.6m)
};
or using for
loop
var list = new List<(int item, string data, decimal value)>();
foreach (var item in Enumerable.Range(1, 3))
list.Add((item, $"data{item}", item));
And access an items like that
var item = list.FirstOrDefault();
var data = item.data;
But keep in mind, that named tuples are available starting from C#7
You can create your own custom class with the property that you want and then make a list out if it
public class MyClass
{
public int ItemA { get; set; }
public string ItemB { get; set; }
public bool ItemC { get; set; }
}
List<MyClass> myList = new List<MyClass>();
and to add an item to the class you simply create a new instance of the class and add it to the list
MyClass myClass = new MyClass
{
ItemA = 1,
ItemB = "hello",
ItemC = true
};
myList.Add(myClass);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With