To check if two dictionaries are equal in C#, you can compare their key-value pairs using the `SequenceEqual` method from the `System.Linq` namespace. This allows you to determine if the dictionaries contain the same elements.
We can check if two dictionaries are equal in C# using the `SequenceEqual` method. This example demonstrates how to declare and initialize two dictionaries, use the `SequenceEqual` method to compare them, and print whether they are equal.
For example,
using System.Collections.Generic;
and using System.Linq;
.firstDict
and secondDict
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize two dictionaries
Dictionary<int, string> firstDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
Dictionary<int, string> secondDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Check if the dictionaries are equal using SequenceEqual
bool areEqual = firstDict.OrderBy(kvp => kvp.Key).SequenceEqual(secondDict.OrderBy(kvp => kvp.Key));
// Print whether the dictionaries are equal
if (areEqual)
{
Console.WriteLine("The dictionaries are equal.");
}
else
{
Console.WriteLine("The dictionaries are not equal.");
}
}
}
The dictionaries are equal.
We can check if two dictionaries are not equal in C# using the `SequenceEqual` method. This example demonstrates how to declare and initialize two dictionaries, use the `SequenceEqual` method to compare them, and print whether they are not equal.
For example,
using System.Collections.Generic;
and using System.Linq;
.firstDict
and secondDict
with integer keys and string values.using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Declare and initialize two dictionaries
Dictionary<int, string> firstDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
Dictionary<int, string> secondDict = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Four"}
};
// Check if the dictionaries are not equal using SequenceEqual
bool areEqual = firstDict.OrderBy(kvp => kvp.Key).SequenceEqual(secondDict.OrderBy(kvp => kvp.Key));
// Print whether the dictionaries are not equal
if (!areEqual)
{
Console.WriteLine("The dictionaries are not equal.");
}
else
{
Console.WriteLine("The dictionaries are equal.");
}
}
}
The dictionaries are not equal.
In this tutorial, we learned How to Check if Two Dictionaries are Equal in C# language with well detailed examples.