0

我有两张相同 K、V 类型的地图,这样

关键是国家

价值是一张地图

所以整体 Map 结构是

 Map <String, Map<String, List<City>>> m1, m2;

现在我想找出地图的哪些条目是相同的,哪些是不同的

例如:

m1 =    { India = [TA -> {City1, City2, City3}   KA -> {City1, City2}]
          USA =   [WI -> {City1, City2, City3},  OH -> {City1, City2}] }

m2 =    { India = [TA -> {City1, City2, City3} ]
          USA =   [WI -> {City1, City3},         DC -> {City1}] }

输出应该是

Common = { India = [TA -> {City1, City2, City3} ]
           USA = [WI -> {City1, City3}] }

有没有比遍历整个列表并逐行检查更好的方法来获取此信息(即使已经定义了这样做的方法,它也会很棒)?

我将使用它,以便我知道在过去几年中唯一改变的是少数几个城市和少数几个州。

如果需要,很乐意进一步澄清。

提前致谢。

4

2 回答 2

1

A lot depends on the type of collection you are going to use to store your data. The other factor is a technology you are going to use. Then it also depends on how efficient versus how readable is your code. My favorite language is C# so I would go for it. Then implement the whole thing - similarly to your suggestion - as Dictionary<string, Dictionary<string, List<City>>>.

To get the data I used LINQ as it gives you quite readable code.

I implemented your example as below (for the sake of simplicity the cities are simple strings):

var m1 = new Dictionary<string,Dictionary<string,List<string>>>
{
    {
        "India", new Dictionary<string, List<string>> 
                    {
                        {"TA", new List<string> {"City1", "City2", "City3"}},
                        {"KA", new List<string> {"City1", "City2"}}
                    }
    },
    {
        "USA", new Dictionary<string, List<string>> 
                    {
                        {"WI", new List<string> {"City1", "City2", "City3"}},
                        {"OH", new List<string> {"City1", "City2"}}
                    }
    }
};

var m2 = new Dictionary<string,Dictionary<string,List<string>>>
{
    {
        "India", new Dictionary<string, List<string>> 
                    {
                        {"TA", new List<string> {"City1", "City2", "City3"}},
                    }
    },
    {
        "USA", new Dictionary<string, List<string>> 
                    {
                        {"WI", new List<string> {"City1", "City3"}},
                        {"DC", new List<string> {"City1"}}
                    }
    }
};

And the operation to get your result is the Intersect method applied on each level of the nested collection:

var result = m1.Keys.Intersect(m2.Keys)
                    .ToDictionary(k => k, k => m1[k].Keys.Intersect(m2[k].Keys)
                        .ToDictionary(l => l, l => m1[k][l].Intersect(m2[k][l])));

If you debug that and expand result you will see it returns the values you expected in your example.

Note, that your City class has to implement the IEquatable<T> interface so it can be correctly processed in the Intersect method. Sample implementation on MSDN

于 2015-04-02T00:17:34.367 回答
1

对于这两个映射,最好的方法是递增每个键。

但是,对于列表,如果列表已排序,则对列表的元素使用二进制搜索

干杯!

于 2015-04-01T22:58:51.657 回答