在孩子的Linq集合中的最小值为了父集合 [英] Order parent collection by minimum values in child collection in Linq
问题描述
Parent{ List<Child> Children {get;set;} }
Child { int Age {get;set;} }
我想自己的孩子的最低年龄责令家长,着手在平局的情况下,第二或第三个孩子。
I would like to order the parents by the lowest age of their children, proceeding to the second or third child in the case of a tie.
最近我'特地是这样的,它只能由孩子中最小的订单:
The closest I've come is this, which only orders by the youngest child:
parents.OrderBy(p => p.Children.Min(c => c.Age))
这没有考虑第二次(或第三,等在平局的情况下)最年轻的。
This doesn't account for second (or third, etc) youngest in the case of a tie.
由于这些3父母相应的子年龄,我想他们在这才能出来。
Given these 3 parents with corresponding child ages, I'd like them to come out in this order.
- P1 1,2,7
- P2 1,3,6
- P3 1,4,5
推荐答案
所以,你现在要做的,在概念层面,是比较两个序列。而不是试图特殊情况下,它为这个特定序列,我们可以简单的写能力比较任意两个序列的比较器。
So what you're trying to do, at a conceptual level, is compare two sequences. Rather than trying to special case it for this specific sequence, we can simply write a comparer capable of comparing any two sequences.
这将通过序列比较中的项目物品在相同的位置,然后,如果发现一对不相等,它知道结果。
It will go through the items in the sequence compare the items at the same position, and then if it finds a pair that aren't equal, it knows the result.
public class SequenceComparer<TSource> : IComparer<IEnumerable<TSource>>
{
private IComparer<TSource> comparer;
public SequenceComparer(IComparer<TSource> comparer = null)
{
this.comparer = comparer ?? Comparer<TSource>.Default;
}
public int Compare(IEnumerable<TSource> x, IEnumerable<TSource> y)
{
return x.Zip(y, (a, b) => comparer.Compare(a, b))
.Where(n => n != 0)
.DefaultIfEmpty(x.Count().CompareTo(y.Count()))
.First();
}
}
现在打电话时<我们可以简单地使用这个比较器code>排序依据:
var query = parents.OrderBy(parent => parent.Children
.OrderBy(child => child.Age)
.Select(child => child.Age)
, new SequenceComparer<int>());
这篇关于在孩子的Linq集合中的最小值为了父集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!