调用 LINQ First() 方法时出现 InvalidArgument 错误
所以我的问题是我在这部分代码中收到无效参数错误。它的目的是拿一手牌并计算它们的总价值之和。然后,如果该值大于 21,它会检查手上是否有任何一张牌是 ace(或者类型是 == ace 并且它的牌totalVal == 11)现在我的问题是我为此编写的语句无论手中是否有 A,都会运行并抛出错误。
我想知道是否有其他方法可以编写下面的语句以使它正确运行?
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;
}
我尝试了几种不同的方法,包括将 != null 更改为 > 0 但是会抛出一个无效参数错误,指出 >不能与该语句一起使用。有没有其他方法可以确定 CurrentCards.First(n => n.Type == 13 && n.Total == 11) 是真还是假?
非常感谢任何帮助或建议。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用
First
,而是使用Any
带有谓词。Instead of
First
, useAny
with the predicate.如果没有匹配的元素,
First
方法将引发异常。您需要调用
FirstOrDefault
,它可能返回null
。The
First
method throws an exception if there are no matching element.You need to call
FirstOrDefault
, which can returnnull
.您应该尝试使用 FirstOrDefault 而不是 First。如果没有返回元素,First 将抛出错误。
另请检查 CurrentCards 是否不为空。如果 IEnumumerable 为空,First 和 FirstOrDefault 都会给出 ArguementNullException。
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.