2

If I instantiate my subclass of List<string>, then I can use Linq's Select method.

using System.Linq;

namespace LinqProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            BetterList list = new BetterList();
            list.Select(l => l.ToString() == "abc");  // no compile error
        }
    }
}

But if I try to use Select within the definition of the subclass...

using System.Collections.Generic;
using System.Linq;

namespace LinqProblem
{
    class BetterList : List<string>
    {
        public List<string> Stuff
        {
            get
            {
                base.Select(l => l.ToString() == "abc");  // compile error
            }
        }
    }
}

Error:

'List<string>' does not contain a definition for 'Select'.

Why is this the case, and is there a work-around?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
  • 8
    There usually isn't much good reason to inherit from `List`, are you sure this is the _best_ way to accomplish your needs? – maccettura Jul 10 '17 at 17:39
  • 3
    https://stackoverflow.com/q/21692193/34397 – SLaks Jul 10 '17 at 17:39
  • @maccettura, I did so because I wanted to add properties that can act as filters - shorthand code for the Linq logic. The code I'm writing will be used by a team, and readability is very important. Is there a better way to achieve the same end? – crenshaw-dev Jul 10 '17 at 17:57
  • Oh I also want to check when an item is added whether there's already an item with the same "key" property. If so, I have logic that handles adding a "duplicate" item sensibly. I did so by overriding the Add method. – crenshaw-dev Jul 10 '17 at 17:59
  • 1
    It sounds like you might want a Dictionary instead of a List. Dictionarys cannot have duplicate keys, it will throw an exception if you try. Also, you should create a class that has a private Dictionary or List as the data store, then expose the date via methods or properties (do your filtering there) – maccettura Jul 10 '17 at 18:02
  • 1
    @maccettura that makes a lot of sense. Thanks for the tip! – crenshaw-dev Jul 10 '17 at 18:06

1 Answers1

11

Select() is an extension method. The base keyword is specifically used to non-virtually call base class methods, and does not support extension methods.

Change it to this.Select and it will work fine.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964