To filter a dictionary based on keys in C#, you can use the `Where` method from the `System.Linq` namespace and convert the filtered result back to a dictionary using the `ToDictionary` method. This allows you to create a new dictionary with the key-value pairs that satisfy a specific condition based on keys.
We can filter a dictionary based on keys in C# using the `Where` method from the `System.Linq` namespace. This example demonstrates how to declare and initialize a dictionary, use the `Where` method to filter the dictionary based on keys, and print the filtered dictionary.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Filter the dictionary to include only keys greater than 1
Dictionary<int, string> filteredDict = myDictionary
.Where(kvp => kvp.Key > 1)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Print the filtered dictionary
Console.WriteLine("Filtered dictionary:");
foreach (var kvp in filteredDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Filtered dictionary: Key: 2, Value: Two Key: 3, Value: Three
We can filter a dictionary to include only specific keys in C# using the `Where` method from the `System.Linq` namespace. This example demonstrates how to declare and initialize a dictionary, use the `Where` method to filter the dictionary to include only the keys 1 and 3, and print the filtered dictionary.
For example,
using System.Collections.Generic;
and using System.Linq;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Filter the dictionary to include only the keys 1 and 3
Dictionary<int, string> filteredDict = myDictionary
.Where(kvp => kvp.Key == 1 || kvp.Key == 3)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// Print the filtered dictionary
Console.WriteLine("Filtered dictionary:");
foreach (var kvp in filteredDict)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Filtered dictionary: Key: 1, Value: One Key: 3, Value: Three
In this tutorial, we learned How to Filter a Dictionary Based on Keys in C# language with well detailed examples.