简体   繁体   中英

Order Collection by child child collection

I have the following objects

public class ObjectA{
    public string Name { get; set; }
    public ICollection<ObjectB> ObjectBCollection { get; set; }
}

public class ObjectB{
    public string Name { get; set; }
    public ICollection<ObjectC> ObjectCCollection { get; set; }
}

public class ObjectC{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public InternalType Type { get; set; }
}

public enum InternalType {
     TypeA,
     TypeB,
     TypeC
}

Now i want to order a List of ObjectA by the Dates in ObjectC that are closests to the current date. To make things a little more interesting, I also want it sorted by the InteralType . But I want TypeB have priority over TypeA and TypeC comes last.

I was thinking of creating an extra value that presents the integer value of the timespan between the current date and the Date property and multiply that by the Type property, but I can't figure out how to actually do that.

First of all if you want specific ordering in Enum you can do this:

public enum InternalType : int
{
     TypeA = 2,
     TypeB = 1,
     TypeC = 3
}

Next if I understood your question correctly you have:

var collection = new List<ObjectA>();

which you need to sort by ALL dates in child elements. You can use Linq expressions for this:

List<KeyvaluePair<DateTime, ObjectA>> collectionWithDates = collection
    .Select
    (
        objectA => new KeyValuePair<DateTime, ObjectA>
        (
            objectA
                .SelectMany(a => a.ObjectBCollection)
                .SelectMany(b => b.ObjectCCollection)
                .OrderBy(c => c.Date).ThenBy(c => (int)c.Type)
                .Last()
                .Date,
            objectA
        )
    )
    .ToList();

To get ordered list of ObjectA you just need to:

var orderedCollection = collectionWithDates
    .OrderBy(d => d.Key)
    .Select(d => d.value)
    .ToList();

I believe this should work. However I didn't tested it. Correct me in comments if I misunderstood requirements.

Last thing to add - as far as I know, Linq expressions are not the fastest way to sort collections.

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