我有这个功能:
ObservableCollection<TankstellenItem> completeList = new ObservableCollection<TankstellenItem>();
for(var j = 0; j < listItem.Count; j++)
{
foreach (FuelItem fItem in listItem.ToList()[j].Fuels)
{
Debug.WriteLine("HERE AGAIN: " + fItem.Price);
TankstellenItem newItem = new TankstellenItem();
ObservableCollection<FuelItem> fuelList = new ObservableCollection<FuelItem>();
newItem = listItem.ToList()[j];
newItem.Fuels = null;
fuelList.Add(fItem);
newItem.Fuels = fuelList;
completeList.Add(newItem);
Debug.WriteLine("PRICES: " + completeList.ToList()[0].Fuels[0].Price);
}
}
Debug.WriteLine("COMPLETELIST LENGTH: " + completeList.ToList()[0].Fuels[0].Price + " + " + completeList.ToList()[1].Fuels[0].Price);
结果是:
LISTITEM LENGTH: 1
HERE AGAIN: 1,699
PRICES: 1,699
HERE AGAIN: 1,529
PRICES: 1,529
COMPLETELIST LENGTH: 1,529 + 1,529
正如你在foreach中看到的那样,价格是不同的。但是在for-method之后,每个项目的输出只有1,529。我不明白为什么会这样。
答案 0 :(得分:0)
从我的代码中可以看出,您希望从原始列表(Fuel
)中的每个TankstellenItem中检索所有listItem
个对象,然后将它们放入ObservableCollection中。
// Create Complete List
ObservableCollection<TankstellenItem> completeList = new ObservableCollection<TankstellenItem>();
// Loop through each TankstellenItem in listItem
foreach(TankstellenItem tItem in listItem) {
// Create an ObservableCollection to store FuelItem objects
ObservableCollection<FuelItem> fuelList = new ObservableCollection<FuelItem>();
// Loop through each FuelItem in the current TankstellenItem
foreach(FuelItem fItem in tItem) {
// Add the FuelItem from current TankstellenItem to the ObservableCollection
Debug.WriteLine("HERE AGAIN: " + fItem.Price);
completeList.Add(new TankstellenItem() {
// Add the FuelItem
Fuels = new ObservableCollection<FuelItem>() {
fItem,
};
}
}
}
尽管如此,如果您只关心FuelItem
,可能更容易拥有FuelItems的集合,而不是将它们包裹在TankstellenItem
内。
ObservableCollection<FuelItem> completeList = new ObservableCollection<FuelItem>();
foreach(TankstellenItem tItem in listItem) {
foreach(FuelItem fItem in tItem) {
completeList.Add(fItem);
}
}
答案 1 :(得分:0)
Linq可能会让这更容易:你真的想要
吗?var completelist=listItem.SelectMany(
i=>i.Fuels.Select(
f=>new TankstellenItem { Fuels=new ObservableCollection<FuelItem>(new[] { f})}
)
).ToList();