如何通过子类属性对父类列表进行排序? [英] How to do order by child class property for a list of parent class?

查看:83
本文介绍了如何通过子类属性对父类列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,父类在子类中有子类,我们通过使用子类的name属性来命名如何按顺序排列父列表.我使用了pq.OrderBy(z => z.Class1.Name!= null).ToList();但该列表未按预期顺序排序.

Here parent class has child class in child class we have name how to make the list of parent as orderby using name property of child class. I used pq.OrderBy(z => z.Class1.Name != null).ToList(); but the list is not ordered as expected.

 class Program
        {
            static void Main(string[] args)
            {
                List<Parent> pq = new List<Parent>() {

                    new Parent () { Class1=new Child () { Name="d" } },
                    new Parent () { Class1=new Child () { Name="s" } },
                    new Parent () { Class1=new Child () { Name="y" } },
                    new Parent () { Class1=new Child () { Name="r" } },
                    new Parent () { Class1=new Child () { Name="b" } },
                    new Parent () { Class1=new Child () { Name="a" } }
                };

                var assa = pq.OrderBy(z => z.Class1.Name != null).ToList();
            }
        }

        public class Parent
        {
            public Child Class1 { get; set; }
        }

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

推荐答案

如果您只想订购列表,可以使用以下方法:

If you just want an ordered List you can use this:

var assa = pq.OrderBy(p => p.Class1.Name).ToList();

如果 Class1 属性可能为null,请使用以下方法:

If it is possible that Class1 property is null use this:

var assa = pq.Where(p => p.Class1 != null).OrderBy(p => p.Class1.Name).ToList();

如果要在结果 List 的末尾包含那些 Class1 为null的对象:

If you want to have those objects where Class1 is null at the end of the resulting List:

var assa = pq.Where(p => p.Class1 != null).OrderBy(p => p.Class1.Name).ToList();
assa.AddRange(pq.Where(p => p.Class1 == null));

这篇关于如何通过子类属性对父类列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆