deed02392
deed02392

Reputation: 5022

LINQ sorting of property List in List of custom object

I have two lists of objects, each object has the property Recommendations which itself is a list of 'Recommendation' objects. I want to sort the recommendation objects based on one of its properties. I have come up with this:

TPSqlORs.Where(x => x.Recommendations != null)
    .ToList()
    .ForEach(y => y.Recommendations.OrderBy(z => z.PointNumber));
SbmReportsORs.Where(x => x.Recommendations != null)
    .ToList()
    .ForEach(y => y.Recommendations.OrderBy(z => z.PointNumber));

But it causes no change at all to the original lists, which makes me suspect the ToList() is just making a copy and the sorting is happening on a copy which gets lost after execution. I searched along these lines but apparently whilst it does make a copy, the new list contains references to the original list elements, so surely it should be sorting them for both lists?

Upvotes: 1

Views: 1151

Answers (4)

Matthew Watson
Matthew Watson

Reputation: 109537

Since Recommendations is in fact a List<Recommendation> you can sort it in-place using List.Sort():

item.Recommendations.Sort((lhs, rhs) => lhs.PointNumber.CompareTo(rhs.PointNumber));

This assumes that item is the object which contains the Recommendations that you want to sort.

If Recommendation elements in the list can be null, you can handle it like this:

item.Recommendations.Sort
(
    (lhs, rhs) =>
    (lhs == null || rhs == null)
    ? Comparer<object>.Default.Compare(lhs, rhs) 
    : lhs.PointNumber.CompareTo(rhs.PointNumber)
);

See List.Sort(Comparison<T> comparison) for details.

Note that List.Sort() is an unstable sort, while Enumerable.OrderBy() is a stable sort, but this is unlikely to make a difference to your case. You need to be aware of the difference though.

[Edit: I have incorporated the code from Jeppe Stig Nielsen's comment below; my thanks to him.]

Upvotes: 2

Anarion
Anarion

Reputation: 2534

Most of the LINQ expressions don't do changes to the source, they return a resulting collection.

Upvotes: 0

Colin Mackay
Colin Mackay

Reputation: 19175

OrderBy will never change the order of the original list. It, along with the other LINQ methods, are pure functions. They don't modify the inputs and only create new outputs.

Upvotes: 2

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

OrderBy is not changing order of list. If you want changing order you should write:

y.Recommendations = y.Recommendations.OrderBy(z => z.PointNumber).ToList()

Read about OrderBy

Upvotes: 4

Related Questions