C#: Multi element list? (Like a list of records): How best to do it?

A List<T> can hold instances of any type - so you can just create a custom class to hold all the properties you want:

public class City
{
   public string Name {get;set;}
   public string Country {get;set;}
}

...

public List<City> GetCities()
{
   List<City> cities = new List<City>();
   cities.Add(new City() { Name = "Istanbul", Country = "Turkey" });
   return cities;
}

public class City
{
    public City(string name, string country)
    {
        Name = name;
        Country = country;
    }

    public string Name { get; private set; }
    public string Country { get; private set; }
}

public List<City> GetCities()
{
    return new List<City>{
        new City("Istanbul", "Turkey"),
        new City("Athens", "Greece"),
        new City("Sofia", "Bulgaria")
    };
}

If you don't really need a list, and it is unlikely that you do, you can make the return type IEnumerable<City>, which is more generic. You can still return a list, but you could also do this:

public IEnumerable<City> GetCities()
{
    yield return new City("Istanbul", "Turkey"),
    yield return new City("Athens", "Greece"),
    yield return new City("Sofia", "Bulgaria")
}

If then you were to loop over cities until you find the first city in Turkey, for example, or the first city that starts with the letter I, you wouldn't have to instantiate all cities, as you would with a list. Instead, the first City would be instantiated and evaluated, and only if further evaluation is required would subsequent City objects be instantiated.


Why is noone mentioning a Dictionary<>?

I think it would be easier to use a Dictionary. From what I understand the OP wants to have 2 values related to each other, in this case, a country and its capital.

Dictionary<string, string> capitals = new Dictionary<string, string>()
{
    {"Istanbul","Turkey"},
    {"Athens","Greece"},
    {"Sofia","Bulgaria"},
};

To add "Key,Values" to your dictionary:

capitals.add("Lisbon, Portugal");

Other possible ways of adding to dictionary

To iterate through the items inside the dictionary:

foreach(KeyValuePair<string, string> entry in capitals)
{
    // do something with entry.Value or entry.Key
}

What is the best way to iterate over a Dictionary in C#?

To edit an entry:

capital[Lisbon]= "..."

Even though creating your own class (or struct I guess) works, if the goal is to create a list that contains 2 values that are related to each other a Dictionary is simpler.

Tags:

C#