我正在try 在列表中查找项目的索引,其中包含类似内容

listx.FindIndex(SomePredicate<T>) 

但我得到了一个错误

NullReferenceResponse:对象引用未设置为对象的实例

起初我不太确定它是什么,所以我也try 使用类似listx.Exists(SomePredicate<T>)的东西.该列表具有固定长度并且确实包含空值(用于在Unity中构建库存系统).

我的(非常)简化代码:

public class Item
{
    public int id;
    public string itemname;

    // constructor etc ...
}

// in another class:

    List<Item> inventory = new List<Item>();

    for (int i = 0; i < 4; i++)
    {
        inventory.Add(null);
    }

    inventory[0] = new Item(0, "YellowBox");
    inventory[1] = new Item(1, "RedBox");
    // inventory[2] stays null
    // inventory[3] stays null

    string itemname = "RedBox";
    inventory.Exists(item => item.itemname == itemname)
    // WORKING because it finds a match before it runs into a null

    string itemname = "BlueBox";
    inventory.Exists(item => item.itemname == itemname)
    // NOT WORKING, I guess because it runs into a null in inventory[2]
    // and it can't get an itemname from null

有人知道首先判断空或有.Exists的替代方案吗?

写这个问题我现在有了一个 idea .我认为仅仅跳过空是不够的,因为我需要索引,但可能是这样的.

public int FindItemIndex(string itemname)
{
    int index;

    for (int i = 0; i < 4; i++)
    {
        if (inventory[i] == null) 
        { 
            index = -1;  
            continue; 
        }

        if (inventory[i].itemname == itemname) 
        {
             return i;
        }

        index = -1;
    }

    return index;
}

然后我可以使用类似的内容:

if (FindItemIndex(string itemname) < 0) 
{ 
    // code for item not found 
}
else 
{ 
    // code where I use the index, for example remove item at inventory[index]
}

或者inventory.Where(Item => Item != null)可以使用吗?

我很感激一些建议

推荐答案

inventory.Exists(item => item?.itemname == itemName)

item?.itemname意味着如果项目不为空,则调用itemName.如果该项为空,则断言解析为null == itemName

Linqs.任何也有效,例如.

var inventoryItemExists = inventory.Any(item => item?.itemName == itemName);

您可以使用其中ie.

var inventoryItemExists = inventory.Where(item => item != null).Any(item => item.itemName == itemName);

Csharp相关问答推荐

我应该将新的httpReportMessage()包装在using声明中吗?

react 式扩展连接中的非交叉LeftDurationTimeout

Blazor. NET 8—阶段启动配置文件不启动网站VS2022

当通过Google的Gmail Api发送邮件时,签名会产生dkim = neutral(正文散列未验证)'

JsonSerializer.Deserialize<;TValue>;(String,JsonSerializerOptions)何时返回空?

为什么我的表单在绑定到对象时提交空值?

无法通过绑定禁用条目

方法从数据表中只 Select 一个条件?

集合表达式没有目标类型

什么时候接受(等待)信号灯?尽可能的本地化?

Linux Docker上的.NET6在某个时间抛出后,在加密操作期间发生System.Security.Cryptography.CryptographicException:错误

如何返回具有泛型的类?

我应该为C#12中的主构造函数参数创建私有属性吗?

在构造函数中传递C#函数以用作EventHandler委托的订阅服务器

如何使用IHostedService添加数据种子方法

Maui:更改代码中的绑定字符串不会更新UI,除非重新生成字符串(MVVM)

在ObservableCollection上使用[NotifyPropertyChangedFor()]源代码生成器不会更新UI

避免在特定区域中设置Visual Studio代码的自动格式

有没有更好的方法来使用LINQ获取整行的计算组

如何使用moq和xUnit对删除操作进行单元测试?