Mike
Mike

Reputation: 3284

Merging keys and values in a dictionary - LINQ

I have class defined like the following:

public class CoinRepository 
    {
        private Dictionary<Coin, int> repository;

        public CoinRepository()
        {
            repository = new Dictionary<Coin, int>();
        }

        public void Add(List<Coin> coins)
        {
            foreach (var coin in coins)
            {
                repository[coin] = repository.ContainsKey(coin) ? repository[coin] + 1 : 1;               
            }
        }      
    }       

   public class Coin
   {
     public int CoinValue { get; set; }
    //Has equals, hascode etc implemented. Omitted here for brevity.
   }

My add method will get called multiple times and I want that foreach loop shortened down by a LINQ query.

Basically what I need to do is group by all the coins by their coinvalues, and then add to the repository. However while doing that I need to merge with the ones which is present there already. How can I achieve this using LINQ?

For example: say I have 2 coins say of value 1 & 2 availiable in the repository,and I get another add request for coins by values 1,2 and 3 then my repository will now have 3 types of coins. Coin with value 1 with count 2, coin with value 2 with count 2 and coin with value 3 with count 1.

Thanks, -Mike

Using .NET 3.5

Upvotes: 0

Views: 616

Answers (3)

spender
spender

Reputation: 120500

This rather assumes you have a collection of coins to process.

It looks like you're trying to build a dictionary of coin vs coin frequency, right? In which case, the solution can be stated in a single line.

var dict = coins.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());

If instead, you're looking to create a dictionary of coin vs total CoinValue :

var dict = coins.GroupBy(c => c)
            .ToDictionary(g => g.Key, g => g.Sum(c => c.CoinValue));

Upvotes: 1

psubsee2003
psubsee2003

Reputation: 8741

LINQ is not an effective tool for executing side effects, it is a query tool. Since you are attempting to modify an existing collection by merging a 2nd collection, it is not the right tool for the job.

Your foreach loop is already pretty effective and probably as fast (or faster) than anything you can with LINQ.

Upvotes: 0

thorn0
thorn0

Reputation: 10417

You can't achieve this with LINQ. LINQ is for querying data structures, not modifying them.

Upvotes: 0

Related Questions