简体   繁体   中英

adding items into list by for loops

I am creating a chart for windows phone 7.

This is the foreach for each hawker returned:

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;


    }

I have to change the above codes to be inside this list of cities:

 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 } };

such as: List<City> cities = new List<City> { new City Name = hawkername, Population = popularity }

so that I can do a bind to my chart:

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

I am not sure how to mix them up, can someone guide me along ? As I do not want to hard code the name and population inside.

that's easy, Just follow the code below.

Declare the list of City Above the foreach loop and on each iteration just add new item to the list

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 });
    }

This fills the cities list as well on the completion of foreach loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM