在C#中需要LINQ ArgumentOutOfRangeException的帮助

时间:2010-06-18 14:10:14

标签: c# linq

希望这是周五问题的一个很好的垒球,但我有以下代码行:

//System.ArgumentOutOfRangeException generated if there is no matching data
currentAnswers = new CurrentAnswersCollection()
    .Where("PARTICIPANT_ID", 10000).Load()[0];

CurrentAnswersCollection是一个强类型集合,由一个返回我的数据库的视图填充。 问题当然是,如果没有相应的PARTICIPANT_ID = 10000,我会收到错误消息。

有没有更好的方法来编写它,以便我根本不会收到错误消息? 我只是不太了解LINQ语法,知道我是否可以先测试存在?

感谢。

4 个答案:

答案 0 :(得分:7)

使用此:

currentAnswers = new CurrentAnswersCollection()
    .Where("PARTICIPANT_ID", 10000).Load()
    .FirstOrDefault();

如果没有第一个元素,它将返回null。

但您可能需要先修复代码(此处复制) - .Where语法看起来很狡猾。

答案 1 :(得分:1)

当您尝试使用索引器从(空)列表中获取第一个项目时,会发生ArgumentOutOfRangeException。使用FirstOrDefault()扩展方法是返回集合的第一个元素的便捷方式(如果有),否则返回null。

currentAnswers = new CurrentAnswersCollection().Where("PARTICIPANT_ID", 10000)
                                               .Load()
                                               .FirstOrDefault();

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.firstordefault.aspx

答案 2 :(得分:0)

你需要在.Where中使用lambda表达式。

currentAnswers = new CurrentAnswersCollection()
    .Where(c => c.PARTICIPANT_ID == 10000).Load().FirstOrDefault(); 

答案 3 :(得分:0)

尝试:

var answers = new CurrenAnswersCollection().Where("PARTICIPANT_ID", 10000);
if(answers.Count() >= 1) currentAnswers = answers.Load()[0];

或类似的东西。