Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a List with 3 columns in C#?

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.

like image 756
LopDev Avatar asked Dec 05 '22 08:12

LopDev


2 Answers

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

like image 183
Pavel Anikhouski Avatar answered Dec 22 '22 00:12

Pavel Anikhouski


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);
like image 21
styx Avatar answered Dec 21 '22 22:12

styx