James213
James213

Reputation: 977

InvalidArgument error when calling LINQ First() method

So my problem is that i am getting an invalid argument error in this section of code. What it is meant to do is take a hand of cards and get the sum of their total value. Then if the value is greater than 21 it checks to see if any of the cards in the hand is an ace(or the type is == ace and it's card totalVal == 11) now my problem is the statement i have written for this will run regardless of if there is an ace in the hand or not and throws an error.

I was wondering if there is any other way i can write the statement below in order to get this to run correctly?

        public int HandTotal()
        {

          int total = CurrentCards.Sum(n => n.Total);
          **while ( total > 21 && CurrentCards.First(n => n.Type == 13 && n.Total == 11) !=null)**
          {                
              CurrentCards.First(n => n.Type == 13).Total = 1;
              total = CurrentCards.Sum(n => n.Total);
              return total;
          }
          return total;
        }

i've tried several different things including changing the != null into > 0 however that throws an invalid argument error saying that > cannot be used with this statement. Is there any other way that i can determine if CurrentCards.First(n => n.Type == 13 && n.Total == 11) is true or false?

Any help or suggestions are greatly appreciated.

Thank You

Upvotes: 3

Views: 164

Answers (3)

Jeremy
Jeremy

Reputation: 6670

You should try using FirstOrDefault instead of First.First will throw an error if no elements a returned. Also check that CurrentCards is not empty. Both First and FirstOrDefault will give an ArguementNullException if the IEnumumerable is empty.

Upvotes: 2

SLaks
SLaks

Reputation: 887807

The First method throws an exception if there are no matching element.

You need to call FirstOrDefault, which can return null.

Upvotes: 2

Oded
Oded

Reputation: 499142

Instead of First, use Any with the predicate.

while(total > 21 && CurrentCards.Any(n => n.Type == 13 && n.Total == 11))

Upvotes: 5

Related Questions