To filter a dictionary based on values 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 values.
We can filter a dictionary based on values 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 values, 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 values that contain the letter 'o'
Dictionary<int, string> filteredDict = myDictionary
.Where(kvp => kvp.Value.Contains("o"))
.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: 2, Value: Two
We can filter a dictionary to include only specific values 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 values 'One' and 'Three', 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 values 'One' and 'Three'
Dictionary<int, string> filteredDict = myDictionary
.Where(kvp => kvp.Value == "One" || kvp.Value == "Three")
.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 Values in C# language with well detailed examples.