split a map into two maps in csharp

To split a map (or a dictionary in c#), you can use LINQ to filter the elements to keep and create two new maps from the result.

Here is an example code that demonstrates how to split a map into two maps, one containing the elements that satisfy a condition, and another containing the remaining elements:

main.cs
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main(string[] args) {
        Dictionary<string, int> map = new Dictionary<string, int>() {
            { "a", 1 },
            { "b", 2 },
            { "c", 3 },
            { "d", 4 },
            { "e", 5 }
        };
        
        // split the map into two maps based on the condition
        Dictionary<string, int> map1 = map.Where(kv => kv.Value <= 3).ToDictionary(kv => kv.Key, kv => kv.Value);
        Dictionary<string, int> map2 = map.Where(kv => kv.Value > 3).ToDictionary(kv => kv.Key, kv => kv.Value);

        Console.WriteLine("Map 1:");
        foreach (var kv in map1) {
            Console.WriteLine(kv.Key + ": " + kv.Value);
        }
        
        Console.WriteLine("Map 2:");
        foreach (var kv in map2) {
            Console.WriteLine(kv.Key + ": " + kv.Value);
        }
    }
}
916 chars
30 lines

In this example, we have a map with string keys and integer values. We split the map into two maps based on the condition that the value is less than or equal to 3 in map1, and greater than 3 in map2. Then, we print the key-value pairs in each new map.

Output:

main.cs
Map 1:
a: 1
b: 2
c: 3
Map 2:
d: 4
e: 5
39 chars
8 lines

related categories

gistlibby LogSnag