Home > OS >  Could not access the First() method when inherited a class from Dictionary in C#
Could not access the First() method when inherited a class from Dictionary in C#

Time:12-12

I can normally use the First() method in a Dictionary type variable like this,

Dictionary<string,string> dic = new Dictionary<string,string>();
dic.Remove(dic.First(kvp => kvp.Value == some_value).Key);

However, when I tried to inherit a class from Dictionary like below it's giving me an error.

class Dic : Dictionary<string, string>
{
   public void DoSomething()
   {
      Remove(First(kvp => kvp.Value == some_value).Key);
   }
}

Error Message This is the error I'm getting.

BTW, First() originates not from Dictionary

Originate

I have tried implementing IEnumerable but it did not help

CodePudding user response:

Your Dic class won't compile as-is. You can use this instead of dic in the class.

class Dic : Dictionary<string, string>
{
    public void DoSomething()
    {
        Remove(this.First(kvp => kvp.Value == "some_value").Key);
    }
}

And then call like this: new Dic().DoSomething();

CodePudding user response:

Why I am inheriting it is because I need to override the default Add() method to check whether the Value is already existing. –

That's what the TryAdd method (either as an extension method or baked in depending on versions) is for. If TryAdd returns false, the value existed; it does not throw an error on duplicate add. You can also use ContainsKey and TryGetValue as alternative ways of checking if a key exists or not

  • Related