简体   繁体   English

用于过滤最新值/记录的 Linq 查询

[英]Linq query to filter on most recent value / record

I have a 'complex' linq query I would like to improve and to understand.我有一个“复杂”的 linq 查询,我想改进和理解。

(from x in tblOrder
 orderby x.OrderNo  
 // where x.Filename is most recent filename for this order
 group x by new { x.OrderNo, x.Color } into groupedByColorCode
 select new
 {
     OrderNo = groupedByColorCode.Key.OrderNo,
     ProductRef = groupedByColorCode.FirstOrDefault().ProductRef,
     Color = groupedByColorCode.Key.Color,
     Packing = groupedByColorCode.FirstOrDefault().Packing,
     TotalQuantity = groupedByColorCode.Sum(bcc => bcc.OriQty).ToString()
 }

x is an Order. x 是订单。 I also would like to filter by Filename.我也想按文件名过滤。 Filename is a variable from tblOrder.文件名是来自 tblOrder 的变量。 Actually I would like to keep and keep only the orders from the most recent file.实际上,我只想保留并保留最新文件中的订单。

What 'where' clause should I add to my linq query to be able to filter these last file name.我应该将什么“where”子句添加到我的 linq 查询中,以便能够过滤这些最后的文件名。

Thank you谢谢

First it's better to use orderby in the end of the query, because sorting will work quicker on the smaller set of data.首先,最好在查询的末尾使用orderby ,因为在较小的数据集上排序会更快。

Second you should use where in the top of query, it will make smaller your set before grouping and sorting (set it after from line)其次,您应该使用查询顶部的where ,它会在分组和排序之前缩小您的集合(在from行之后设置)

At last grouping creates dictionary with Key = new { x.OrderNo, x.Color } (in this keys) and Value = IEnumerable , and then groupedByColorCode becomes IEnumerabler of {Key, Value} .最后分组使用Key = new { x.OrderNo, x.Color } (在这个键中)和Value = IEnumerable创建字典,然后groupedByColorCode成为{Key, Value} 的IEnumerabler So it should stand in the end before orederby所以它应该站在orederby之前

如果您需要某些条件的最大值或最小值,则有 MaxBy() 或 MinBy()

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

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