Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 索引超出范围。必须为非负数且小于集合的大小。。。参数名称:index";_C#_Asp.net_Entity Framework - Fatal编程技术网

C# 索引超出范围。必须为非负数且小于集合的大小。。。参数名称:index";

C# 索引超出范围。必须为非负数且小于集合的大小。。。参数名称:index";,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,我不知道为什么会发生这种错误。请帮帮我 索引超出范围。必须为非负数且小于集合的大小。参数名称:索引 这是我的密码: var index = newData.FindIndex(x => x.description == item.description); if (index ==-1) index = 0; var itemInIndex = newData[index]; 我得到的错误在这行,上面写着: var ite

我不知道为什么会发生这种错误。请帮帮我

索引超出范围。必须为非负数且小于集合的大小。参数名称:索引

这是我的密码:

var index = newData.FindIndex(x => x.description == item.description);
                           
if (index ==-1)
    index = 0;

var itemInIndex = newData[index];
我得到的错误在这行,上面写着:

var itemInIndex = newData[index];

首先检查您的新数据列表是否为空。 因为它是空的,您试图获取第一个元素,但该元素不存在。 异常基本上告诉您正在尝试索引一个不存在的元素

编辑:阅读@Charlieface发布的链接,了解有关异常和索引的更多信息。

请检查:

与match定义的条件相匹配的元素的第一次出现的从零开始的索引(如果找到);否则,-1

在您的代码逻辑中有以下顺序:

[从newData获取索引,其中description==item.description]

[检查索引是否为==-1]

[然后asign索引=0]

[从newData[0]获取结果]

这意味着您正在强制索引0(它在数组、列表等中不可用)


看看如何管理异常:

这是否回答了您的问题?
var index=newData.FindIndex(x => x.description== item.description);      

if (index ==-1) throw new ArgumentNullException("description not found!");

var itemInIndex = newData[index];