William YK
William YK

Reputation: 1125

Using Linq to select subset from a Dictionary<string, int>?

I'm newer to C# and I'm trying to use LINQ (or another method?) to select a subset of a Dictionary<string, int> object where the value (int) is greater than 5.

+-------------+------------+
| Key(string) | Value(int) |
+-------------+------------+
|         000 |          0 |
|         111 |          1 |
|         222 |          2 |
|         333 |          3 |
|         444 |          4 |
|         555 |          5 |
|         666 |          6 |
|         777 |          7 |
|         888 |          8 |
|         999 |          9 |
+-------------+------------+

I created the dictionary object above with this code to simply fill a dictionary with some data:

        Dictionary<string, int> linkCounter = new Dictionary<string, int>();

        for (int i=0; i<=9; i++)
        {
            string key = i.ToString() + i.ToString() + i.ToString();
            for (int n=0; n<=i; n++)
            {
                if (linkCounter.ContainsKey(key))
                {
                    linkCounter[key]++;
                }
                else
                {
                    linkCounter.Add(key, 0);
                }
            }
        }

How can I do something equivalent to:

foreach (KeyValuePair<string, int> kvp in linkCounter [where kvp.value > 5])

Upvotes: 1

Views: 4208

Answers (3)

Gauravsa
Gauravsa

Reputation: 6524

Something like this:

var keyValueSet = linkCounter.Where(p => p.Value > 5);
keyValueSet.ForEach(i => Console.WriteLine(i.Key + ": " + i.Value));

Upvotes: 0

A.Darwaz
A.Darwaz

Reputation: 43

var subset = linkCounter
    .Where(w => w.Value > 5)
    .ToDictionary(k => k.Key, v => v.Value);

Like mentioned in the answer above, what Linq returns is an IEnumerable<kvp<K,V>> when you operate on a dictionary. If you want to get a dictionary back you can use the method I used in the method above to convert the Enumerable back to a dictionary.

Upvotes: 1

Roman Marusyk
Roman Marusyk

Reputation: 24579

add

using System.Linq;

and then use Where

var subset = linkCounter.Where(x => x.Value > 5);
foreach(KeyValuePair<string, int> kvp in subset)
{
   // your code
}

Upvotes: 1

Related Questions