按特定键C#

时间:2015-10-27 21:01:55

标签: c# list dictionary

我有两个不同长度的词典列表。两个字典中的键都是相同的,值可能不是。

var A = List<Dictionary<string, object>>();
var B = List<Dictionary<string, object>>();

我想基于包含在其中的字典对象中的3个键的值来交叉A和B.

例如:

var dict = new Dictionary<string,object>{{"W",val1},{"X",val2},{"Y",val3},{"Z",val4}}

类似于上面的词典包含在列表A和B中,其中val1,val2,val3,val4的值不同。如果键W,X,Y的值相等,我想要交叉A和B,但我不关心交叉点的Z值。有没有办法优雅地实现这一目标?

以一个例子阐述:

   A.add(new Dictionary<string,object>{{"W",123},{"X",456},{"Y",789},{"Z",103}});
   A.add(new Dictionary<string,object>{{"W",124},{"X",456},{"Y",789},{"Z",893}});
   A.add(new Dictionary<string,object>{{"W",123},{"X",456},{"Y",789},{"Z",134}});

   B.add(new Dictionary<string,object>{{"W",123},{"X",456},{"Y",789},{"Z",900}});
   B.add(new Dictionary<string,object>{{"W",124},{"X",456},{"Y",789},{"Z",893}});
   B.add(new Dictionary<string,object>{{"W",212},{"X",321},{"Y",789},{"Z",134}});

如果我做A.intersect(B),我想回到以下列表,

{"W",123},{"X",456},{"Y",789},{"Z",103}
{"W",123},{"X",456},{"Y",789},{"Z",900}
{"W",124},{"X",456},{"Y",789},{"Z",893}

1 个答案:

答案 0 :(得分:2)

这会给你一个IEnumerable:

var c=A.Select(a=>new {W=a[W],X=a[X],Y=a[Y]})
  .Intersect(B.Select(a=>new {W=a[W],X=a[X],Y=a[Y]}));

或者,创建自己的自定义IEqualityComparer,然后就可以执行此操作:

var c=A.Intersect(B,new MyComparer());

类似的东西:

class MyComparer : IEqualityComparer<Dictionary<string,object>>
{
    public bool Equals(Dictionary<string,object> b1, Dictionary<string,object> b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null || b2 == null)
           return false;
        else if(b1["W"]==b2["W"] && b1["X"]==b2["X"] && b1["X"]==b2["X"])
            return true;
        else
            return false;
    }

    public int GetHashCode(Dictionary<string,object> bx)
    {
        int hCode = bx["W"] ^ bx["X"] ^ bx["Y"];
        return hCode.GetHashCode();
    }
}