Behrooz Karjoo
Behrooz Karjoo

Reputation: 4292

Using an extension method on a dictionary

I am not sure how to use an extension method on a dictionary. How do I specify that I need the function applied to the value and not the key?

Here's a sample code applying the Sum extension method on a list of doubles and a dictionary whose values are doubles. The list extension methods works fine but the dictionary extension method is asking for a selector function.

    static void Main(string[] args)
    {
        List<double> list = new List<double>();
        list.Add(34.2);
        list.Add(234);
        Console.WriteLine(list.Sum());

        Dictionary<string, double> dictioanary = new Dictionary<string, double>();
        dictioanary.Add("a", 5.34);
        dictioanary.Add("b", 44);

        Console.WriteLine(dictioanary.Sum());
        Console.ReadKey();
    }

Upvotes: 1

Views: 1835

Answers (4)

Rob
Rob

Reputation: 27357

You have to pass a lambda to the Sum() function:

Console.WriteLine(dictioanary.Sum(kvp => kvp.Value));

Upvotes: 3

Jim Schubert
Jim Schubert

Reputation: 20357

A dictionary's Values property is a ICollection<T>. (Link) Instead of writing your own extension method, you should use Linq's extensions.

using System.Linq;

 static void Main(string[] args)
    {
        List<double> list = new List<double>();
        list.Add(34.2);
        list.Add(234);
        Console.WriteLine(list.Sum());

        Dictionary<string, double> dictioanary = new Dictionary<string, double>();
        dictioanary.Add("a", 5.34);
        dictioanary.Add("b", 44);

        Console.WriteLine(dictioanary.Values.Sum()); // See?
        Console.ReadKey();
    }

Upvotes: 0

Muad&#39;Dib
Muad&#39;Dib

Reputation: 29226

i would do something like this:

public static int MyExtension<valueType,keyType>(this Dictionary<valueType,keyType> dict )
{
  return dict.Values.Sum();
}

Upvotes: 1

SLaks
SLaks

Reputation: 887469

You can use the dictionary's Values collection.

Upvotes: 1

Related Questions