Reputation: 1
I have a Hashtable containing a struct and am trying to use a foreach loop to access elements within each struct. However the output will only give me the value title rather than let me get at the data within. When I try to use CityDetail.City it will only give the most recent item stored in CityDetail rather than checking the Hashtable. Any advice on how to handle this would be gratefully appreciated, thanks.
Hashtable CityDataHT = new Hashtable();
CityData CityDetail = new CityData();
for(int i = 0; i <10; i++)
{
//code for getting the various elements for city detail
CityDetail.City = SplitCity[0];
CityDetail.Region = SplitCity[1];
CityDetail.Country = SplitCity[2];
CityDetail.Latitude = Latitude;
CityDetail.Longitude = Longitude;
CityDataHT.Add(Convert.ToString(i), CityDetail);
}
foreach (int k in CityDataHT.Keys)
{
Console.WriteLine(CityDataHT[k]);
// this line just gives the value title - IP_Project+CityData
}
public struct CityData
{
public string City, Region, Country, Latitude, Longitude, Distance;
public CityData(string p1, string p2, string p3, double p4, double p5, Int32 p6)
{
City = p1;
Region = p2;
Country = p3;
Latitude = Convert.ToString(0);
Longitude = Convert.ToString(1);
Distance = Convert.ToString(2);
}
}
Upvotes: 0
Views: 767
Reputation: 1948
In order for your loop to print something else you'd need to define what to print:
foreach (int k in CityDataHT.Keys)
{
CityData city = (CityData)CityDataHT[k];
Console.WriteLine(
city.City + " - " +city.Country
);
// Prints "City - Country"
}
Upvotes: 1