2015-10-14 42 views
1

我有物品清單,並檢查物品是否存在於清單中。如果存在,我嘗試找到它。如果它存在,查找項目

我認爲它有一點開銷,因爲我目前在列表上做了兩遍。是否可以單程執行?

目前我有。

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; 
} 
+6

這是一個有點不清楚你問什麼,但似乎你正在尋找'FirstOrDefault()'我猜。 – CodeCaster

+0

@CodeCaster但是,如果數據不是唯一的,它可能會返回一個不正確的數據。 – Greg

+0

編輯代碼以顯示什麼是「數據」。基本查找返回null如果找不到任何東西? –

回答

0

所以FirstOrDefault()是要走的路。如果只有該列表中的一個項目,也可以使用SingleOrDefault()

static stub = new Item() { text = "NaN", id = -1 }; 
    public static Item get(int i) 
    { 
     Item result; 
     result = data.FirstOrDefault(f => f.id == i); 

     if (result == null) 
     { 
      return stub; 
     } 

     return result; 
    } 
3

你似乎在尋找FirstOrDefault()

Item _stub = new Item 
{ 
    text = "NaN", 
    id = -1 
}; 

public Item FindByID(int id) 
{ 
    // Find the first item that has the provided id, or null if none exist. 
    var existingItem = data.FirstOrDefault(i => i.id == id); 

    // When not found, return the _stub 
    return existingItem ?? _stub; 
} 

你也可能需要重新考慮您的命名約定,你是否真的需要這些成員是static

+0

謝謝,它看起來不錯。靜態是好的('sub'和'data'是這個類的全局只讀實體)。無法理解名稱有什麼問題。 –

+0

@Stepan閱讀[MSDN:Naming Guidelines](https://msdn.microsoft.com/en-us/library/xzf533w0(v = vs.71).aspx),特別是[MSDN:大寫樣式](https:/ /msdn.microsoft.com/en-us/library/x2dbyw72(v=vs.71).aspx)。公共方法通常應該是'PascalCased'。此外,方法名稱「get」及其名稱爲「i」的參數並不具有真正的描述性。 – CodeCaster

2

您可以使用List.FindIndex

public static Item get(int i) 
{ 
    int index = data.FindIndex(item => item.id == i); 
    if (index == -1) return stub; 
    return data[index]; 
} 

如果它實際上是一個數組,你可以使用Array.FindIndex

public static Item get(int i) 
{ 
    int index = Array.FindIndex(data, item => item.id == i); 
    if (index == -1) return stub; 
    return data[index]; 
} 
+0

FindIndex()也很好。無法理解我錯過了這種方法。 –

0

我想你可以試試這個:

return data.Find(f => f.id == i) ?? stub; 
+1

已更新的示例。 –

0

我使用完全用於此目的的擴展方法

public static T FirstOrSpecificDefault<T>(this IEnumerable<T> list, 
             Func<T, bool> predicate, T defaultValue) 
{ 
    return list.FirstOrDefault(predicate) ?? defaultValue; 
} 

使用你的情況是

Item result = list.FirstOrSpecificDefault(f => f.id == i, stub); 
相關問題