C#按内部属性列表排序

时间:2016-02-23 23:03:48

标签: c# list collections

假设我有一个像这样的对象..

public class Child
{
    public string Name {get;set;}
    public int Age {get;set;}
}

public class Mother
{
    public string Name {get;set;}
    public Child child;
}

现在我有一份母亲名单

List<Mother> 

我已订购List<Child>

孩子与母亲一对一。

我想根据List<Child>

的顺序订购母亲名单

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

如果这些名单是相同的,并且所有母亲都有孩子,反之亦然,那么这是开箱即用的。如果母亲多于孩子或母亲的孩子不在孩子的名单上,那么这些母亲不会返回。同样,如果孩子的母亲或母亲不在母亲名单上的孩子多,那么这些孩子的主持人就不会被退回。

public IEnumerable<Mother> GetOrderedMothersByChildren(
    IEnumerable<Mother> mothers, IEnumerable<Child> children)
{
    foreach (var child in children)
    {
        var mother = mothers.FirstOrDefault(m => m.Child == child);
        if (mother != null)
            yield return mother;
    }
}

//Usage
var orderedMothers = GetOrderedMothersByChildren(mothers, children).ToList();