排序父/子对象列表

时间:2014-11-29 04:10:55

标签: linq sorting

我在确定如何根据子项有效地对父项列表进行排序时遇到了一些麻烦。

我不能只对子项进行排序。我需要子项排序的结果来影响父列表的排序。

基本上我要做的就是按顺序对父母进行排序,以便按照降序反映孩子的姓名。

是否有" linqish"一旦我已经有一份记忆中的父母列表,这样做的方法是什么?如果是这样,你能负担得起的任何帮助都会很棒。

这是一个例子......

//What I am trying to do is to figure out how to sort the order of parent1, parent2, parent3 
//based on the names of their children. 
//More specifically, the expected output would be:
//parent 1 (because she has a child with the name of Zoey), 
//parent 3 (because she has a child next in desc order with the name of Yolanda), 
//parent 2 (because her child names in desc order would Matt).

public class Parent
{
    public int id { get; set; }
    public int SortOrder { get; set; }
    //some properties
    public List<Child> Children { get; set; }

    public static List<Parent> GetSortedParentsByChildName()
    {
        List<Parent> myUnsortedList = new List<Parent>()
        {
            new Parent()
            {
                id = 1,
                Children = new List<Child>()
                {
                    new Child(1, "Billy"),
                    new Child(1, "Zoey"),
                    new Child(1, "Robert"),
                }
            },
            new Parent()
            {
                id = 2,
                Children = new List<Child>()
                {
                    new Child(1, "Gabe"),
                    new Child(1, "Matt"),
                    new Child(1, "Alyssa"),
                }
            },
            new Parent()
            {
                id = 3,
                Children = new List<Child>()
                {
                    new Child(1, "Will"),
                    new Child(1, "Bob"),
                    new Child(1, "Yolanda"),
                }
            },
        };


        return myUnsortedList; //.OrderBy(my actual question);
    }
}

public class Child
{
    public int id { get; set; }
    //some properties
    public string Name { get; set; }

    public Child(int id, string Name)
    {
        this.id = id;
        this.Name = Name;

    }
}

2 个答案:

答案 0 :(得分:2)

好的,你也可以这样做: -

List<Parent> mySortedList =
    myUnsortedList
        .OrderByDescending(
            x => x.Children.OrderByDescending(z => z.Name).First().Name)
        .ToList();

答案 1 :(得分:0)

我可以替换return中的GetSortedParentsByChildName行:

        var childrenMap =
            myUnsortedList
                .SelectMany(x => x.Children)
                .Select(x => x.Name)
                .Distinct()
                .OrderBy(n => n)
                .Select((n, i) => new { n, i })
                .ToDictionary(x => x.n, x => x.i);

        return myUnsortedList
            .Select(x => new
            {
                x,
                max = x.Children
                    .Select(y => childrenMap[y.Name])
                    .Max()
            })
            .OrderByDescending(x => x.max)
            .Select(x => x.x)
            .ToList();

我得到了这个结果:

parents in order