Ive been trying to get OrderBy
in a LINQ statement to work with an anonymous object but have failed by now.
I checked these already:
Anonymous IComparer implementation
C# linq sort - quick way of instantiating IComparer
How to sort an array of object by a specific field in C#?
I spent a few hours trying different approaches but there has to be something I'm missing.
Let's say there's the following class:
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public int Popularity {get; set;}
public decimal Price {get; set;}
}
And products
is a list of these objects.
How can I complete this LINQ statement, so that it works with the anonymous object ?
To be clear, I know I can do this in a different way but I'd be very interested to learn how to make this particular example work.
var sortedProducts = products
.OrderBy(p =>
new {p.Popularity, p.Price},
[IComparer magic goes here]);
It seems that it should be possible with an implementation of the ProjectionComparer
:
http://code.google.com/p/edulinq/source/browse/src/Edulinq/ProjectionComparer.cs?r=0c583631b709679831c99df2646fc9adb781b2be
Any ideas how to do this ?
UPDATE:
I did a quick performance test on this - the anonymous comparer solution vs standard orderby.thenby and it seems that the anonymous solution is quite slower which is probably what we might have expected anyway.
numProd | Anon | chained orderby clauses
10 000 | 47 ms | 31 ms
100 000 | 468 ms | 234 ms
1 000 000| 5818 ms | 2387 ms
5 000 000| 29547 ms| 12105 ms
products.OrderByDescending(p => p.Popularity).ThenBy(p => p.Price)
– Sampson