【发布时间】:2021-03-15 09:13:58
【问题描述】:
如何在 c# 中将 3 个单独的列表合并为一个具有 3 个列或字段的列表?
我尝试使用 3 个 foreach 循环将 3 个单独的列表添加/组合到每个列或字段到一个列表中,但它一次只添加一个列/字段,并且列表是我需要的 3 倍是并且只有一列/字段的数据,而其他两列/字段为空或零。像这样:
0 0 3.701
0 0 3.633
0 0 3.622
0 0 3.623
我需要它是这样的:
12 2020 3.623
这是我的代码。
List<GasPrices> listOfGasPrices = new List<GasPrices>()
{
new GasPrices() { Month = 11, Year = 1942, Price = 3.333 }
};
foreach (var month in intMonthList)
{
listOfGasPrices.Add(new GasPrices { Month = month });
}
foreach (var year in intYearList)
{
listOfGasPrices.Add(new GasPrices { Year = year });
}
foreach (var price in doublePriceList)
{
listOfGasPrices.Add(new GasPrices { Price = price });
}
for (int k = 0; k < listOfGasPrices.Count; k++)
{
Console.WriteLine(listOfGasPrices[k].Month + " " + listOfGasPrices[k].Year + " " + listOfGasPrices[k].Price);
}
class GasPrices
{
//backing fields
private int _month, _year;
private double _price;
//constructor
public GasPrices()
{
_month=0;
_year=0;
_price=0;
}
//getter and setters of properties
public int Month { get; set; }
public int Year { get; set; }
public double Price { get; set; }
}
【问题讨论】: