重复代码使用时出错

时间:2017-04-18 02:03:36

标签: c# indexof

有人可以解释为什么我收到'System.InvalidOperationException:'Sequence中没有匹配的元素''错误在下面的第三行?它与第1行完全相同,唯一改变的是我使用索引修改了列表中项目的数据字段,但修改的数据与搜索查询无关。列表中始终有数据。

int index = junctions.IndexOf(junctions.First(item => item.coOrds == currentPos));
junctions[index].possibleDir[0] = true;
index = junctions.IndexOf(junctions.First(item => item.coOrds == currentPos));

额外信息

不确定是否相关,但coOrds和currentPos字段是Tuple<int, int>,possibleDir是bool[]。 Junctions是一个自定义类Junction的列表。

如果我使用以下其他选项之一,则会出现同样的问题;

var value = junctions.First(item => item.coOrds == currentPos);
var value = junctions.Find(item => item.coOrds == currentPos);

关注

似乎它与Tuple比较有关,下面的行工作正常。我不知道为什么上面的第一行工作(现在仍然如此)但不一致。

index = junctions.IndexOf(junctions.First(item => item.coOrds.Item1 == currentPos.Item1 && item.coOrds.Item2 == currentPos.Item2));

1 个答案:

答案 0 :(得分:0)

  

First(IEnumerable)方法抛出异常if   source不包含任何元素。而是在返回时返回默认值   源序列为空,使用FirstOrDefault方法。

参考链接:MDSN

您应该使用FirstOrDefault并检查空