I have a C# class that inherits from a collection. I make heavy use of LINQ, so calls to my class methods are intermingled with LINQ calls. Unfortunately this means that I frequently cast the IEnumerable<> returned by LINQ back into my class type in the middle of a pipeline. This results in excess code, and it is computationally inefficient.
Another solution is to implement the class methods as extension methods. This is more efficient, but in this case I will end up having to reproduce functionality that I could inherit from a collection.
Is there a way to inherit from collections, but still efficiently interact with LINQ?
The following program contains two queries. The first query calls a method from a derived class, but it also requires an O(n) call to ToMyList(). The second query is more efficient, but it is not making use of a derived class.
using System.Collections.Generic;
using System.Linq;
namespace StackOverflow
{
// A custom list that can multiply every element by a constant integer.
public class MyList : List<int>
{
public MyList() : base() { }
public MyList(IEnumerable<int> items) : base(items) { }
public MyList Multiply(int n)
{
for(int i = 0; i < Count; ++i)
this[i] *= n;
return this;
}
}
public static class Extensions
{
// Convert from IEnumerable<int> to MyList.
public static MyList ToMyList(this IEnumerable<int> items)
{
return new MyList(items);
}
// An extension version of the multipy method.
public static IEnumerable<int> Multiply(this IEnumerable<int> items, int n)
{
foreach (var item in items)
yield return n * item;
}
}
class Program
{
static void Main(string[] args)
{
// Create a large list.
var myList = new MyList();
for (int i = 0; i < 1000000; ++i) myList.Add(i);
// Call the MyList.Multiply method.
var query1 = myList.Skip(100).ToMyList().Multiply(5);
// Call the extension version of the Multiply method.
var query2 = myList.Skip(100).Multiply(5);
}
}
}