查找项目(如果存在)

时间:2015-10-14 15:35:57

标签: c# list

我有项目列表,我检查列表中是否存在项目。如果它存在,我试图找到它。

我认为它有一点开销,因为我目前在列表上进行两次传递。是否有可能单次通过?

目前我有。

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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];
}

答案 2 :(得分: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 :(得分:0)

我想你可以试试这个:

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

答案 4 :(得分:0)

我正是为了这个目的而使用扩展方法

rake db:migrate:down VERSION=20151014152222

在你的情况下使用

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