【问题标题】:Using LINQ within a 'foreach' loop only running once在仅运行一次的“foreach”循环中使用 LINQ
【发布时间】:2020-08-20 10:57:18
【问题描述】:

这是一个游戏。当他们加载游戏时,我正在尝试将玩家的物品重新加载到他们的库存中。下面的“itemStrings”是玩家保存游戏时所有项目名称的字符串列表。代码如下:

void Load(){ List<string> itemStrings = SaveLoad.Load<List<string>>("Inventory");

        foreach(string nameString in itemStrings)
        {
            loadReference = itemDatabase.itemsDatabaseList.Where(obj => obj.name == nameString).First();
            bool wasAdded = instance.Add(loadReference);
    }}

作为参考,itemDatabase 是对一个类 ItemDatabase 的引用。存储游戏中的每个项目。 loadreference 是一个名为 Item 的类,它在此 Inventory 类的开头声明。

我要做的是在数据库中搜索名称与 itemStrings 中的字符串匹配的项目,然后获取该项目并将其添加到玩家的库存中。这个“foreach”对 itemStrings 列表中的第一项正常工作,但它只运行一次。所以它只会将一件物品加载到库存中,无论之前保存了多少。

【问题讨论】:

标签: c# list linq loops foreach


【解决方案1】:

我会重写你的内部查询,只返回一个请求中的所有值。

void Load()
{ 
  var inventory = SaveLoad.Load<List<string>>("Inventory")
    .Join(itemDatabase.itemDataList, name=>name, item=>item.name, (name,item)=>item);
  // Use one of the following three methods:
  instance.AddRange(inventory);
  // or if instance is just a List of items then...
  instance = inventory.ToList();
  // or if there is no AddRange, and instance is not just a List:
  foreach(var item in inventory)
  {
    instance.Add(item);
  }
}

或者,为自己创建一个 GetInventory 方法:

IEnumerable<Item> GetInventory()
{ 
  return SaveLoad.Load<List<string>>("Inventory")
    .Join(itemDatabase.itemDataList, name=>name, item=>item.name, (name,item)=>item);
}

然后你可以在你的 Load 方法中做任何你想做的事情。

【讨论】:

  • 非常感谢,这行得通!我遇到了一个问题,它没有返回多个项目实例,但是由于某种原因切换到 for 循环而不是 foreach 可以正常工作。再次感谢!
【解决方案2】:

发生这种情况是因为您的 loadReference 是在其他地方定义的,所以您只是在更改指针(基本上每次都复制先前加载的项目)。

void Load()
{ 
    List<string> itemStrings = SaveLoad.Load<List<string>>("Inventory");

    foreach(string nameString in itemStrings)
    {
        var item = itemDatabase.itemsDatabaseList.Where(obj => obj.name == nameString).First();
        bool wasAdded = instance.Add(item);
    }
}

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多