0

我有这个功能:

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 方法之后,每个项目的输出只有 1,529。我不明白为什么会这样。

4

2 回答 2

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

 }

虽然,如果您只关心FuelItems,拥有 FuelItems 的集合而不是将它们包装在TankstellenItem.

 ObservableCollection<FuelItem> completeList = new ObservableCollection<FuelItem>();
 foreach(TankstellenItem tItem in listItem) {
      foreach(FuelItem fItem in tItem) {
           completeList.Add(fItem);
      }
 }
于 2012-11-14T13:30:35.417 回答
0

Linq 可能会让这更容易:你真的想要

var completelist=listItem.SelectMany(
       i=>i.Fuels.Select(
          f=>new TankstellenItem { Fuels=new ObservableCollection<FuelItem>(new[] { f})}
       )
   ).ToList();
于 2012-11-14T14:31:54.303 回答