简体   繁体   English

在LINQ查询期间获取行中的最小值

[英]Get min value in row during LINQ query

I know that I can use .Min() to get minimum value from column, but how to get minimum value in a row? 我知道我可以使用.Min()从列中获取最小值,但是如何连续获得最小值?

I have following LINQ query (for testing purposes): 我有以下LINQ查询(用于测试目的):

from p in Pravidloes
where p.DulezitostId == 3
where p.ZpozdeniId == 1 || p.ZpozdeniId == 2
where p.SpolehlivostId == 2 || p.SpolehlivostId == 3

group p by p.VysledekId into g
select new {
  result = g.Key,
  value = g
}

Which results into this: 结果如下:
linqqueryimage

I would however like to get only the MIN value of following three columns: 但是,我想只获得以下三列的MIN值
DulezitostId, ZpozdeniId, SpolehlivostId as a value in: DulezitostId,ZpozdeniId,SpolehlivostId作为值:

select new {
  result = g.Key,
  value = g // <-- here
}

The final result then should look like: 最终结果应如下所示:
result: 2, value: 1 结果:2,值:1
result: 3, value: 2 结果:3,价值:2

I have been looking for similar questions here and googled for few examples with grouping and aggregating queries, but found nothing that would move me forward with this problem. 我一直在寻找类似的问题,并搜索了几个关于分组和聚合查询的例子,但没有发现任何会让我前进的问题。

Btw: Solution isn't limited to linq, if you know better way how to do it. 顺便说一句:解决方案不仅限于linq,如果您知道更好的方法。

You could create an array of the values and do Min on those. 您可以创建值的数组并对其执行Min。

select new {
  result = g.Key,
  value = g.SelectMany(x => new int[] { x.DulezitostId, x.ZpozdeniId, x.SpolehlivostId }).Min()
}

This will return the min for those 3 values in each grouping for ALL rows of that grouping. 这将返回该分组的所有行的每个分组中的3个值的最小值。

Which would result in something like this... 哪会导致这样的......

result: 3, value: 1 结果:3,值:1

The below will select the min for each row in the grouping... 以下将为分组中的每一行选择最小值...

select new {
  result = g.Key,
  value = g.Select(x => new int[] { x.DulezitostId, x.ZpozdeniId, x.SpolehlivostId }.Min())
}

Which would result in something like this... 哪会导致这样的......

result: 3, value: 1, 2 结果:3,值:1,2

The best solution if you're using straight LINQ is Chad's answer . 如果您使用直接LINQ,最好的解决方案是Chad的答案 However, if you're using Linq To SQL it won't work because you can't construct an array like that. 但是,如果您使用Linq To SQL,它将无法工作,因为您无法构建类似的数组。

Unfortunately, I believe the only way to do this in Linq To Sql is to use Math.Min repeatedly: 不幸的是,我相信在Linq To Sql中执行此操作的唯一方法是重复使用Math.Min:

select new {
  result = g.Key,
  value = Math.Min(Math.Min(DulezitostId, ZpozdeniId), SpolehlivostId)
}

This will generate some ugly CASE WHEN ... statements, but it works. 这将生成一些丑陋的CASE WHEN ...语句,但它有效。

The main advantage of doing it this way is that you're only returning the data you need from SQL (instead of returning all 3 columns and doing the Min in the application). 这样做的主要优点是,您只需从SQL返回所需的数据(而不是返回所有3列并在应用程序中执行Min )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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