Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric extension method to convert from one collection to another
    primarykey
    data
    text
    <p>I'm working in a code base which has a lot of first class collections.</p> <p>In order to ease using these collections with LINQ, there is an extension method per collection that looks like:</p> <pre><code>public static class CustomCollectionExtensions { public static CustomCollection ToCustomCollection(this IEnumerable&lt;CustomItem&gt; enumerable) { return new CustomCollection(enumerable); } } </code></pre> <p>With the accompanying constructors:</p> <pre><code>public class CustomCollection : List&lt;CustomItem&gt; { public CustomCollection(IEnumerable&lt;CustomItem&gt; enumerable) : base(enumerable) { } } </code></pre> <p>This winds up being a bunch of boilerplate so I attempted to write a generic <code>IEnumerable&lt;U&gt;.To&lt;T&gt;()</code> so that we wouldn't have to keep generating these specific ToXCollection() methods.</p> <p>I got as far as:</p> <pre><code>public static class GenericCollectionExtensions { public static T To&lt;T, U&gt;(this IEnumerable&lt;U&gt; enumerable) where T : ICollection&lt;U&gt;, new() { T collection = new T(); foreach (U u in enumerable) { collection.Add(u); } return collection; } } </code></pre> <p>Which has to be called like <code>customCollectionInstance.OrderBy(i =&gt; i.Property).To&lt;CustomCollection, CustomItem&gt;()</code></p> <p>Is there a way to avoid having to specify the <code>CustomItem</code> type so we can instead use <code>customCollectionInstance.OrderBy(i =&gt; i.Property).To&lt;CustomCollection&gt;()</code> or is this not something that can be done generically?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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