我有物品清單,並檢查物品是否存在於清單中。如果存在,我嘗試找到它。如果它存在,查找項目
我認爲它有一點開銷,因爲我目前在列表上做了兩遍。是否可以單程執行?
目前我有。
public partial class Item
{
public string text;
public int id;
}
....
static List<Item> data = new List<Item>();
static stub = new Item() { text = "NaN", id = -1 };
public static Item Get(int targetId)
{
if (data.Any(f => f.id == targetId) == false)
{
return stub;
}
return data.Find(f => f.id == targetId);
}
我想是這樣
...
public static Item Get(int targetId)
{
Item result;
result = data.Find(f => f.id == targetId);
if (result == null)
{
return stub;
}
return result;
}
這是一個有點不清楚你問什麼,但似乎你正在尋找'FirstOrDefault()'我猜。 – CodeCaster
@CodeCaster但是,如果數據不是唯一的,它可能會返回一個不正確的數據。 – Greg
編輯代碼以顯示什麼是「數據」。基本查找返回null如果找不到任何東西? –