I like lists, because they are very easy to use and manage. However, I have a need for a list of multiple elements, like records.
I am new to C#, and appreciate all assistance! (Stackoverflow rocks!)
Consider this straightforward, working example of a single element list, it works great:
public static List<string> GetCities()
{
List<string> cities = new List<string>();
cities.Add("Istanbul");
cities.Add("Athens");
cities.Add("Sofia");
return cities;
}
If I want the list to have two properties for each record, how would I do it? (As an array?)
E.g. what is the real code for this pseudo code?:
public static List<string[2]> GetCities()
{
List<string> cities = new List<string>();
cities.Name,Country.Add("Istanbul","Turkey");
cities.Name,Country.Add("Athens","Greece");
cities.Name,Country.Add("Sofia","Bulgaria");
return cities;
}
Thank you!
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;
}
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