Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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!

like image 816
Jonesome Reinstate Monica Avatar asked Nov 20 '11 05:11

Jonesome Reinstate Monica


1 Answers

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;
}
like image 196
BrokenGlass Avatar answered Oct 04 '22 08:10

BrokenGlass