如何在没有循环的情况下在List类中找到元素?
例如使用循环查找普通查找:
for(int i = 0; i < inventoryx.Player.items.Count; i++) {
if(inventoryx.Player.items[i].itemName == "Wood") {
Debug.log("You Find The Wood");
}
else {
Debug.Log("Can't Find The Wood");
}
}
items.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// Make Class Item
public class item {
public string itemName;
public int itemID;
public string itemDesc;
public string itemIcon;
public GameObject itemModel;
public int itemTime;
public int hightprice;
public int stdprice;
public int itemStock;
public int harvest;
public RawTree rawTree;
public ItemType itemType;
public ItemProd itemProd;
public ItemLocation itemLocation;
public int Lvlunlock;
private string baseName;
public int itemExp;
public enum ItemType {
Raw,
Admirable,
Valuable
}
public enum RawTree {
BigTree,
SmallTree,
Field,
None
}
public enum ItemProd {
Corps,
Dairy,
JuiceJamMaker,
Kitchen,
Bakery,
CraftHouse,
ChickenCoop,
FishingSpotMountain,
CowPasture,
LunaMine,
PigPen,
FishingSpotLake,
TropicalWood,
SheepPasture,
FishingSpotSea,
Beebox,
HomeIndustry
}
public enum ItemLocation {
Home,
Orchard
}
public item (string name, int ID, string desc, int harvestx, int time, int stdpricex, int hightpricex, int stock, int Lvlunlockx, RawTree RawTree, ItemType type, ItemProd prod, string folderx, ItemLocation location, int Exp) {
itemName = name;
itemID = ID;
itemDesc = desc;
harvest = harvestx;
itemTime = time;
stdprice = stdpricex;
hightprice = hightpricex;
itemStock = stock;
Lvlunlock = Lvlunlockx;
rawTree = RawTree;
itemType = type;
itemProd = prod;
itemIcon = folderx;
itemLocation = location;
itemExp = Exp;
}
public item() {
}
}
有没有想法找到没有上面循环的项目? 因为使用循环来查找元素数据需要更多的内存来完成它。如果有超过100个项目,它将使其滞后并花费更多时间。
由于
答案 0 :(得分:3)
为了提高许多项目的效率,您可以考虑创建字典,将itemName
映射到项目:
Dictionary<string, Item> itemNamesToItem = inventoryx.Player.items.ToDictionary(i => i.itemName, i => i);
然后您可以按名称访问项目:
if (itemNamesToItem.ContainsKey("Wood"))
Debug.log("You Find The Wood");
else
Debug.Log("Can't Find The Wood");
当然,如果itemName
是唯一的,您只能这样做。而且你可能应该为每个玩家存储这个字典,也许作为播放器的属性,所以你不必每次想要查找一个项目时重新创建它。
如果itemName
不是唯一的,您可以考虑将itemName
字典映射到项目列表:
Dictionary<string, List<Item>> itemNamesToItem =
inventoryx.Player.items.GroupBy(i => i.itemName)
.ToDictionary(g => g.Key, g => g.ToList());
答案 1 :(得分:2)
使用LINQ你可以写
using Sytem.Linq;
...
bool hasWood = inventoryx.Player.items.Any(i => i.ItemName == "Wood");
或者,找到索引:
int index = items.FindIndex(i => i.ItemName == "Wood");
返回与条件匹配的第一个项的索引,或-1表示未找到匹配项。
这仍然是O(n),就像你的循环一样,但它更简洁,更易读。
此外,C#提供foreach
语句来迭代IEnumerable
个集合,这有助于防止异常异常:
foreach (var item in inventoryx.Player.items)
{
if (item.ItemName == "Wood")
Debug.log("You Find The Wood");
}