简体   繁体   中英

c# Linq sort List by member of nested List

I've got

List<ObjectA> 
ObjectA is a List<ObjectB> 
ObjectB is List<ObjectC>

One of ObjectC is class with field ID (I could specify it) and field "Name"

var result = List<ObjectA>
.OrderBy(t => t.ObjectB[1]    
.ObjectC   
.Where(c => c.ID.Equals("ID"))  
.FirstOrDefault().Name)
  • it works.

I want to NOT use strong index for ObjectB. Something like

var result = List<ObjectA>
.OrderBy(t => t.ObjectB.Where(s=>s
.ObjectC
.Where(c => c.ID.Equals("ID"))
.FirstOrDefault().Name)
  • of course it not works:).

So, how could I sort List by Name?

Thanks.

It seems that you can leverage using SelectMany to flatten the nested collections. Should look something like this:

var result = List<ObjectA>
    .OrderBy(t => t.ObjectB
        .SelectMany(s => s.ObjectC)
        .Where(c => c.ID.Equals("ID"))
        .FirstOrDefault()?.Name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM