我有一个记录对象队列如下:
public class Record
{
public string TypeDesc { get; set; }
public Queue<Total> Totals { get; set; }
etc.....
}
我在写LINQ表达式来提取一个子集时遇到了麻烦,该子集只有每个TypeDesc中的一个,但在每个TypeDesc中,总数队列中Total对象最多的一个。
我不确定它是否重要,但只有一个TypeDesc在Totals队列属性中具有Total对象。所有其他队列都是空的。大约有8个唯一的TypeDesc值。
这是我的尝试,但是total属性在"s"上不可用。
var records =记录。选择(c => c. typedesc)。在哪里(s => s.Totals.Count) .Max () .Distinct ();
- 按
TypeDesc
属性对记录进行分组 - 每组选择
Totals.Count
值最高的组
records.GroupBy(r => r.TypeDesc)
.Select(
g => g.Aggregate((acc, current) => current.Totals.Count > acc.Totals.Count
? current
: acc));
对于像这样的复杂查询,最好将逻辑分解一点,以使代码更具可读性:
Func<IEnumerable<Record>, Record> mostTotals =
group => group.Aggregate(
(acc, current) => current.Totals.Count > acc.Totals.Count
? current
: acc);
var records = records.GroupBy(r => r.TypeDesc)
.Select(mostTotals);
步骤2是通过使用Aggregate
来实现的,它遍历该组中的记录,并使用一个"累加器"来跟踪每次迭代时Totals.Count
最高的记录。
为了简化,聚合函数等价于:
//for each group
Record acc = null;
foreach(var current in group)
acc = current.Totals.Count > acc.Totals.Count
? current
: acc;