简体   繁体   中英

Linq query to filter on most recent value / record

I have a 'complex' linq query I would like to improve and to understand.

(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. I also would like to filter by Filename. Filename is a variable from 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.

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.

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)

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} . So it should stand in the end before orederby

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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