Max或默认? [英] Max or Default?

查看:192
本文介绍了Max或默认?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是从一个LINQ查询可能不返回行的最大价值的最佳方法是什么?如果我只是做

What is the best way to get the Max value from a LINQ query that may return no rows? If I just do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter).Max

我得到一个错误时,该查询返回任何行。我可以做

I get an error when the query returns no rows. I could do

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select y.MyCounter _
         Order By MyCounter Descending).FirstOrDefault

但感觉有点钝了这样一个简单的要求。我缺少一个更好的方式来做到这一点?

but that feels a little obtuse for such a simple request. Am I missing a better way to do it?

更新:这是后面的故事:我正在尝试从一个子表的下一个资格计数器(遗留系统,不要让我开始...)。第一资格行对于每个患者始终为1,第二个是2等。(显然这不是子表的主键)。所以,我选择了最大的现有计数器值的患者,再加入1,可以创建一个新的行。如果没有现有的子值,我需要查询返回0(因此​​增加1会给我的计数值1)。请注意,我不想依靠子行的原始计数,以防遗留应用程序引入了国内空白的计数器值(可能的)。我的坏试图使这个问题太一般。

UPDATE: Here's the back story: I'm trying to retrieve the next eligibility counter from a child table (legacy system, don't get me started...). The first eligibility row for each patient is always 1, the second is 2, etc. (obviously this is not the primary key of the child table). So, I'm selecting the max existing counter value for a patient, and then adding 1 to it to create a new row. When there are no existing child values, I need the query to return 0 (so adding 1 will give me a counter value of 1). Note that I don't want to rely on the raw count of child rows, in case the legacy app introduces gaps in the counter values (possible). My bad for trying to make the question too generic.

推荐答案

由于DefaultIfEmpty没有在LINQ落实到SQL,我做了它返回该错误的搜索和发现的有趣的文章与空集聚合函数处理。要总结一下我发现,您可以通过转换成在您选择一个可空绕开这一限制。我VB是有点生疏,但我的它会去是这样的:

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select CType(y.MyCounter, Integer?)).Max

或者在C#

var x = (from y in context.MyTable
         where y.MyField == value
         select (int?)y.MyCounter).Max();

这篇关于Max或默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆