Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

c# - How to do order by child class property for a list of parent class?

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; }
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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();

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...