最大还是默认? [英] Max or Default?

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

问题描述

从可能不返回任何行的 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 to 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();

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

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