pierre
pierre

Reputation: 1245

Order complex object via LINQ

I have a complex object:

+ Client
     + Products
           + Types
               | TypeId
               | ManagerCode
               | TypeName
                ....

A single client will be associated with a collection of products they have bought, and each product will have a collection of types associated with it.

I need to sort the 'Types' on two properties - ManagerCode and TypeName.

eg: client.Products.ForEach(o => o.Types.OrderBy(o1 => o1.BaseType.ManagerCode));

Well, when I do this, the list doesn't actually order once returned to the front end. It maintains the original sort order. What am I doing wrong?

Upvotes: 0

Views: 180

Answers (2)

Will
Will

Reputation: 895

An alternative solution would be to use the Sort method.

client.Products.ForEach(o => o.Types.Sort(
    (x, y) => string.Compare(x.BaseType.ManagerCode, y.BaseType.ManagerCode));

Upvotes: 1

Rawling
Rawling

Reputation: 50184

OrderBy doesn't replace the original collection; it returns a newly-sorted collection.

Assuming Types is a list, you need

client.Products.ForEach(o =>
    o.Types = o.Types.OrderBy(o1 => o1.BaseType.ManagerCode).ToList());

Upvotes: 2

Related Questions