假设我有一个代表订单行的类,例如
public class Line
{
public string Code ;
public string No ; // Invoice Number
public DateTime Date ;
public string Product ;
public decimal Quantity ;
}
和行列表,例如
List<Line> myList = new List<Line>();
myList.Add(new Line() { Code = "ABC001", No = "1001" ,Date = new DateTime(2012,4,1) , Product = "X", Quantity= 1m});
myList.Add(new Line() { Code = "ABC001", No = "1001" ,Date = new DateTime(2012,4,1) , Product = "Y", Quantity= 1m});
myList.Add(new Line() { Code = "ABC002", No = "1002" ,Date = new DateTime(2012,4,2) , Product = "X", Quantity= 1m});
myList.Add(new Line() { Code = "ABC002", No = "1002" ,Date = new DateTime(2012,4,2) , Product = "Y", Quantity= 1m});
myList.Add(new Line() { Code = "ABC002", No = "1003" ,Date = new DateTime(2012,4,3) , Product = "Z", Quantity= 1m});
myList.Add(new Line() { Code = "ABC002", No = "1004" ,Date = new DateTime(2012,4,4) , Product = "X", Quantity= 1m});
myList.Add(new Line() { Code = "ABC003", No = "1005" ,Date = new DateTime(2012,4,4) , Product = "X", Quantity= 1m});
myList.Add(new Line() { Code = "ABC003", No = "1006" ,Date = new DateTime(2012,4,4) , Product = "X", Quantity= 1m});
myList.Add(new Line() { Code = "ABC003", No = "1006" ,Date = new DateTime(2012,4,4) , Product = "Y", Quantity= 1m});
我希望检索客户代码包含多张发票的所有行。为此,我首先按代码、编号和日期分组,然后按客户代码分组,对于有两条或更多记录的任何客户,我选择除第一条记录之外的所有记录。
像这样:
var query1 =
(from r in myList
group r by new { r.Code , r.No , r.Date } into results
group results by new { results.Key.Code } into results2
where results2.Count() > 1
select new
{
results2.Key.Code ,
Count = results2.Count(),
Results = results2.OrderBy(i=>i.Key.Date).Skip(1).ToList()
// Skip the first invoice
}
).ToList();
query1 现在包含正确的记录,但包含在 IGrouping 中,我无法将结果作为List<Line>
我试过 query1.SelectMany(r=>r.Results).ToList();
但这仍然给我留下了 IGrouping ,这就是我卡住的地方。
我可以使用嵌套的 for 循环,如
List<Line> output = new List<Line>();
foreach (var r1 in query1)
{
foreach(var r2 in r1.Results)
foreach(var r3 in r2)
output.Add(r3);
}
但有更好的/Linq 方式吗?
实际输出应该是四行,如
// Code No Date Product Quantity
// ABC002 1003 03/04/2012 00:00:00 Z 1
// ABC002 1004 04/04/2012 00:00:00 X 1
// ABC003 1006 04/04/2012 00:00:00 X 1
// ABC003 1006 04/04/2012 00:00:00 Y 1