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

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?)

Eg 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!


一个List<T>可以容纳任何类型的实例 - 所以你可以创建一个自定义类来容纳你想要的所有属性:

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.


对于即时处理,您可以使用元组(在.NET 4.0中):

List<Tuple<string,string>> myShinyList = new List<Tuple<string,string>> {
    Tuple.Create("Istanbul","Turkey"),
    Tuple.Create("Athens","Greece"),
    Tuple.Create("Sofia","Bulgaria")
}
链接地址: http://www.djcxy.com/p/30394.html

上一篇: Dictionary.ElementAt方法在某些类中可见,但不是其他类

下一篇: C#:多元素列表? (如记录列表):如何最好地做到这一点?