簡體   English   中英

如何按子類屬性為父類列表排序?

[英]How to do order by child class property for a list of parent class?

在這里,父類在子類中具有子類,我們通過使用子類的name屬性來命名如何將父列表作為訂單。 我使用了pq.OrderBy(z => z.Class1.Name!= null).ToList(); 但是列表未按預期順序排序。

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

如果您只想要有序列表,可以使用以下命令:

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

如果Class1屬性可能為null,請使用以下命令:

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

如果要在結果List的末尾具有Class1為null的那些對象:

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

只需使用Name屬性作為調用OrderBy函數的參數,即可獲得所需的結果:

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

您的代碼中的問題是您提供了一個用於確定順序的布爾標准。 由於列表中所有根據此條件檢查的元素都將返回true->順序保持不變。 您可以通過將最后一項的名稱設置為null

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=null } }

在這種情況下,您的原始查詢將導致最后一項的排序為第一個

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

問題是您的訂購功能:

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

如果您注意到,則從該函數返回一個布爾值:

z => z.Class1.Name != null

您想要的是返回Name屬性的值:

z => z.Class1.Name

更改為此:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM