首页 > 解决方案 > 在 C# 中比较字典中的数组

问题描述

我正在尝试比较字典中存在的数组,如果数组相同则传递键。我正在使用类似这样的语法来检查值,任何人都可以帮助使用正确的语法。

Dictionary<int, string[]> test = excel.GetSheetColumnPairs(xlWorkbook, myint);
//loop dictionary all elements   
foreach (KeyValuePair<int, string[]> pair in test)
{
    Console.WriteLine(pair.Key + "....." + pair.Value + "<br />");
}
//find dictionary duplicate values.  
var duplicateValues = test.GroupBy(x => x.Value).Where(x => x.Count() > 1);

Console.WriteLine("<br /><b>dictionary duplicate values..........</b><br />");

//loop dictionary duplicate values only            
foreach (var item in duplicateValues)
{
    Console.WriteLine(item.Key + "<br />");
}

标签: c#

解决方案


Assuming that the keys are always different and your code don't explode: The GroupBy is using the equality implementation for arrays. By default two arrays will be equal if they are referencing the same object (the same array); i.e: the default equality implementation won't care about the elements of the array, it only test that the referenced object are the same object. If you want to know if two arrays (different references, different objects in memory) contains the same elements, you have to create your own method and compare the elements one by one(or you can override the equality implementation)


推荐阅读