How to filter a map in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var myDictionary = new Dictionary<int, string>
        {
            { 1, "C#" },
            { 2, "C" },
            { 3, "C++" },
            { 4, "Java" },
            { 5, "Python" }
        };

        // Filter: Keep only entries where the key is greater than 2
        var filteredDictionary = myDictionary
            .Where(kv => kv.Key > 2)
            .ToDictionary(kv => kv.Key, kv => kv.Value);

        foreach (var kv in filteredDictionary) {
            Console.WriteLine($"Key: {kv.Key}, Value: {kv.Value}");
        }
    }
}



/*
run:

Key: 3, Value: C++
Key: 4, Value: Java
Key: 5, Value: Python

*/

 



answered Aug 6, 2025 by avibootz

Related questions

1 answer 78 views
1 answer 145 views
3 answers 110 views
3 answers 114 views
1 answer 82 views
82 views asked Aug 7, 2025 by avibootz
...