[Solved] List with numbers and text


There are many options, I describe some of them for you

  1. use Dictionary<int, string>
    Pros: very fast lookup
    Cons: you can not have two string with same number, you don’t have a List

    var list2d = new Dictionary<int, string>();
    list2d[1] = "hello";
    list2d[2] = "world!";
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value);
    }
    
  2. use Tuple<int, string>
    Pros: very simple and handy tool, you have a List
    Cons: Tuples are immutable, you can not change their values once you create them, reduces code readability (Item1, Item2)

    var list2d = new List<Tuple<int, string>>();
    list2d.Add(new Tuple(1, "hello"));
    list2d.Add(Tuple.Create(1, "world");
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Item1, item.Item2);
    }
    
  3. use a defined class,
    Pros: you have a List, very customizable
    Cons: you should write more code to setup

    public class MyClass
    {
       public int Number { get; set; }
       public string Text { get; set; }
    }
    
    var list2d = new List<MyClass>();
    list2d.Add(new MyClass() { Number = 1, Text = "hello" });
    list2d.Add(new MyClass { Number = 2, Text = "world" });
    foreach (var item in list2d)
    {
        Console.WriteLine(string.Format("{0}: {1}", item.Number, item.Text);
    }
    

solved List<> with numbers and text