简体   繁体   中英

Need help with a LINQ ArgumentOutOfRangeException in C#

Hoping this is a nice softball of a question for a friday but I have the following line of code:

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

CurrentAnswersCollection is a strongly-typed collection populated by a view going back to my database. The problem of course is that if there is not a corresponding PARTICIPANT_ID = 10000 I get the error message.

Is there a better way to write this so that I wouldn't get the error message at all? I just dont know enough about LINQ syntax to know if I can test for the existance first?

thanks.

Use this:

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

It'll return null if there is no first element.

But you may need to fix your code (replicated here) first - the .Where syntax looks dodgy.

The ArgumentOutOfRangeException is occurring when you try to use the indexer to get the first item from the (empty) list. Using the FirstOrDefault() extension method is a convenient way to return the first element of a collection, if there is one, otherwise to return null.

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

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

You need a lambda expression in .Where.

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

Try:

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

or something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM