LINQ-如何获得最小值,如果值= 0,获取下一个值
-
25-10-2019 - |
题
我有一个测试数据库,该数据库可记录从商店登录到商店门户的数据以及它持续多长时间。
示例:(仅出于可视化目的 - 不是实际的数据库)
Stores
Id Description Address City
1 Candy shop 43 Oxford Str. London
2 Icecream shop 45 Side Lane Huddersfield
Connections
Id Store_Ref Start End
1 2 2011-02-11 09:12:34.123 2011-02-11 09:12:34.123
2 2 2011-02-11 09:12:36.123 2011-02-11 09:14:58.125
3 1 2011-02-14 08:42:10.855 2011-02-14 08:42:10.855
4 1 2011-02-14 08:42:12.345 2011-02-14 08:50:45.987
5 1 2011-02-15 08:35:19.345 2011-02-15 08:38:20.123
6 2 2011-02-19 09:08:55.555 2011-02-19 09:12:46.789
我需要从数据库中获取各种数据。我已经获得了最大和平均连接持续时间。 (因此可能非常不言而喻。.)我还需要提供一些有关哪种连接持续的信息。我当然立即想到了linq的min()函数,但是如您所见,数据库还包括开始和结束的连接。因此,该数据实际上并不是对数据分析的“有效”。
因此,我的问题是如何获得最小值,但是如果值= 0,则获取最低的下一个值。
到目前为止,我的LINQ查询(哪个实现min()函数):
var min = from connections in Connections
join stores in Stores
on connections.Store_Ref equals stores.Id
group connections
by stores.Description into groupedStores
select new
{
Store_Description = groupedStores.Key,
Connection_Duration = groupedStores.Min(connections =>
(SqlMethods.DateDiffSecond(connections.Start, connections.End)))
};
我知道可以通过多个查询和/或语句获取有效值,但是我想知道是否可以在一个查询中完成所有问题,因为我的程序期望返回LINQ查询,而我的偏好是保持该程序尽可能“轻”。
如果您必须做好/简单的方法才能这样做,请分享。您的贡献非常感谢! :)
解决方案
var min = from connections in Connections.Where(connections => (SqlMethods.DateDiffSecond(connections.Start, connections.End) > 0)
join stores in Stores
on connections.Store_Ref equals stores.Id
group connections
by stores.Description into groupedStores
select new
{
Store_Description = groupedStores.Key,
Connection_Duration = groupedStores.Min(connections =>
(SqlMethods.DateDiffSecond(connections.Start, connections.End)))
};
尝试一下,通过过滤“ 0”值,您将获得正确的结果,至少是我所教的。
其他提示
如果您添加,请在选择新的内容之前,将条款在对照期间的持续时间内使用类似的内容:
let duration = SqlMethods.DateDiffSecond(connections.Start, connections.End)
然后添加一个子句
where duration != 0
在计算最小值之前,请在其中包含一个子句。
groupedStores.Where(conn => SqlMethods.DateDiffSecond(conn.Start, conn.End) > 0)
.Min(conn => (SqlMethods.DateDiffSecond(conn.Start, conn.End))
不隶属于 StackOverflow