嵌套的foreach放入C#中的字符串数组中
本文关键字:字符串 数组 放入 foreach 嵌套 | 更新日期: 2023-09-27 18:29:36
所以我有一个包含酒店信息的数组,我需要其中的一部分是每个酒店的位置,这样我就可以将其发送到不同的方法中。所以我有了我的第一个foreach设置,但现在我想知道如何将位置上的所有数据收集到一个字符串数组中,以便在读取所有酒店后发送出去。有人能帮忙吗,谢谢。
// API call to get the info
ContentAPI.BasicHotelMedia[] rawData = DataHelper.NewContentAPI().GetBasicHotelMedia(ProductCode, ProductYear, SiteBrand);
//setting up the datatable
DataTable dtHotels = InitHotelTable();
//set my variables
foreach (ContentAPI.BasicHotelMedia item in rawData)
{
DataRow dr = dtHotels.NewRow();
dr["HotelCode"] = item.BasicHotelCode;
dr["HotelDescription"] = item.BasicDescription;
dr["WiFi"] = item.HasWifi;
// This is the variable that i need set in the string array so i can send into another method
dr["SellingLocation"] = item.BasicSellingLocation;
// Add other raw data
// Get other info about the hotel
GetHotelMedia(item.BasicHotelCode, ProductYear, item.HasWifi, ref dr);
dtHotels.Rows.Add(dr.ItemArray);
}
我建议使用List,而不是初始化字符串[]。它们只是更容易使用。像这样:
var locations = new List<string>();
foreach (ContentAPI.BasicHotelMedia item in rawData)
{
...
locations.Add(item.BasicSellingLocation);
}
OtherMethod(locations.ToArray());