Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ OrderBy anonymous object with projection comparer
    primarykey
    data
    text
    <p>Ive been trying to get <code>OrderBy</code> in a LINQ statement to work with an anonymous object but have failed by now.</p> <p>I checked these already:<br> <a href="https://stackoverflow.com/questions/5288963/anonymous-icomparer-implementation">Anonymous IComparer implementation</a><br> <a href="https://stackoverflow.com/questions/1381564/c-sharp-linq-sort-quick-way-of-instantiating-icomparer">C# linq sort - quick way of instantiating IComparer</a><br> <a href="https://stackoverflow.com/questions/1301822/how-to-sort-an-array-of-object-by-a-specific-field-in-c/1302185#1302185">How to sort an array of object by a specific field in C#?</a><br></p> <p>I spent a few hours trying different approaches but there has to be something I'm missing.</p> <p>Let's say there's the following class:</p> <pre><code>public class Product { public int Id {get; set;} public string Name {get; set;} public int Popularity {get; set;} public decimal Price {get; set;} } </code></pre> <p>And <code>products</code> is a list of these objects.<br></p> <p>How can I complete this LINQ statement, so that it works with the anonymous object ?<br> 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.<br></p> <pre><code>var sortedProducts = products .OrderBy(p =&gt; new {p.Popularity, p.Price}, [IComparer magic goes here]); </code></pre> <p>It seems that it should be possible with an implementation of the <code>ProjectionComparer</code>:<br> <a href="http://code.google.com/p/edulinq/source/browse/src/Edulinq/ProjectionComparer.cs?r=0c583631b709679831c99df2646fc9adb781b2be" rel="nofollow noreferrer">http://code.google.com/p/edulinq/source/browse/src/Edulinq/ProjectionComparer.cs?r=0c583631b709679831c99df2646fc9adb781b2be</a><br></p> <p>Any ideas how to do this ?</p> <p>UPDATE:</p> <p>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.</p> <pre><code> 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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload