通过for循环将项添加到列表中

时间:2014-02-05 06:41:36

标签: c# windows-phone-7 charts silverlight-3.0

我正在为Windows Phone 7创建一个图表。

这是每位小贩返回的预告:

void dbSvc_retrievepopularhawkerCompleted(object sender, RouteServiceRef.retrievepopularhawkerCompletedEventArgs e)
{
    List<RouteServiceRef.Hawker> recommendPlaceList;
    recommendPlaceList = e.Result.Cast<RouteServiceRef.Hawker>().ToList();

    string hawkername = "";
    string address = "";
    string postal = "";
    double coordX = 0.0;
    double coordY = 0.0;
    double popularity = 0;



    foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
    {
        hawkername = rp.hawkername;
        address = rp.address;
        postal = rp.postal;
        coordX = rp.xcoord;
        coordY = rp.ycoord;
        popularity = rp.popularity;


    }

我必须将上述代码更改为此城市列表:

 List<City> cities = new List<City> { new City { Name = "CLE", Population = 2250871 }, new City { Name = "CMH", Population = 1773120 }, new City { Name = "CVG", Population = 2155137 }, new City { Name = "DET", Population = 4425110 } };

例如:List<City> cities = new List<City> { new City Name = hawkername, Population = popularity }

这样我就可以绑定到我的图表了:

 ColumnSeries bs = ChartControl.Series[0] as ColumnSeries; bs.ItemsSource = cities;

我不确定如何混淆它们,有人可以引导我吗?因为我不想对内部的名称和人口进行硬编码。

1 个答案:

答案 0 :(得分:2)

这很简单,只需按照下面的代码即可。

声明City的列表在foreach循环之上并且在每次迭代时只需将新项添加到列表中

List<City> cities = new List<City> ();

foreach (RouteServiceRef.Hawker rp in recommendPlaceList)
    {
        hawkername = rp.hawkername;
        address = rp.address;
        postal = rp.postal;
        coordX = rp.xcoord;
        coordY = rp.ycoord;
        popularity = rp.popularity;
        cities.Add(new City(){Name = hawkername, Population = popularity });
    }

这也填写了城市列表以及foreach循环的完成。