Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>list</code> is a collection of elements to be sorted.<br/> <code>pattern</code> is a collection of elements in specific order.<br/> <code>result</code> is a collection of elements from <code>list</code> ordered according to the <code>pattern</code>. <br/></p> <pre><code>var list = new List&lt;Foo&gt; { new FooA(), new FooB(), new FooC(), new FooA(), new FooC(), new FooA(), new FooD() }; var pattern = new Foo[] { new FooB(), new FooC(), new FooD(), new FooA() }; var result = list.OrderBy(p =&gt; p, new MyFooComparer(pattern)); </code></pre> <p>There is a class <code>MyFooComparer</code> that implements interface <code>IComparer&lt;&gt;</code>.<br/> Comparison is based on the position of each <code>Foo</code> in <code>pattern</code> collection. <code>pattern</code> elements <strong>must not be duplicated</strong> and they must contain all types of <code>Foo</code> (at least those used in <code>list</code>).<br/> I used <code>Dictionary&lt;&gt;</code> to store the pattern order because it has O(1) complexity. </p> <pre><code>public class MyFooComparer : IComparer&lt;Foo&gt; { private readonly Dictionary&lt;Type, int&gt; _pattern; public MyFooComparer(IEnumerable&lt;Foo&gt; pattern) { _pattern = new Dictionary&lt;Type, int&gt;(); int i = 0; foreach (var foo in pattern) { _pattern.Add(foo.GetType(), i); i++; } } public int Compare(Foo x, Foo y) { var xVal = _pattern[x.GetType()]; var yVal = _pattern[y.GetType()]; return xVal.CompareTo(yVal); } } </code></pre> <p>After calling:</p> <pre><code> foreach (var foo in result) { Console.WriteLine(foo.GetType().Name); } </code></pre> <p>According to the <code>pattern</code>, you will get:</p> <pre><code>FooB FooC FooC FooD FooA FooA FooA </code></pre> <p><strong>EDIT:</strong></p> <p>Extension for <code>List&lt;Foo&gt;</code>:</p> <pre><code>static class MyExtension { public static IEnumerable&lt;Foo&gt; OrderByFoo&lt;T&gt;(this List&lt;Foo&gt; list, IEnumerable&lt;Foo&gt; patern) { return list.OrderBy(p =&gt; p, new MyFooComparer(patern)); } } </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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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