比较两个列表

时间:2011-02-02 10:51:55

标签: c# linq asp.net-mvc-2

我有两个清单。我应该比较2个列表,并且应该从列表中获取公共值,我应该将它放在字符串数组中...

First List ....

List<string> IDs = new List<string>();
Dictionary<string, Test> group = TestProxy.GetNames(IDs.ToArray());

第二份清单......

List<string> Names = new List<string>();
Dictionary<string, Test> groupNames = TestProxy.GetSections(Names.ToArray());

如何采取共同的价值......

更新了代码....

        List<string> IDs = new List<string>();
        modulesIDs.Add("ID1");
        Dictionary<string, Group> group = PrivilegeProxy.GetNames(IDs.ToArray());

        List<string> Roles = new List<string>();
        Roles.Add("Role1");
        Dictionary<string, Role> Role = PrivilegeProxy.GetRoles(Roles.ToArray());


        Dictionary<string, "******"> common = group.Intersect(Role).ToDictionary(x => x.Key, x => x.Value);

        return common;

在“common”字典中我应该给出哪个对象(“Dictionary common”)

1 个答案:

答案 0 :(得分:4)

使用Enumerable.IntersectEnumerable.ToDictionary

    Dictionary<string, Test> commonGroups = group.Intersect(groupNames)
        .ToDictionary(x=>x.Key, x => x.Value);

更新:如果怀疑仍然存在,请阅读此内容。 Recreating a Dictionary from an IEnumerable