Skip to main content
 首页 » 编程设计

c#之比较两个列表

2024年02月23日23xxx_UU

我有 2 个列表。我应该比较这两个列表,并从两个列表中获取公共(public)值,我应该将它放在一个字符串数组中...

第一个列表....

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()); 

如何取共同值(value)观...

更新代码....

        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; 

在“常用”词典中我应该给哪个对象(“常用词典”)

请您参考如下方法:

使用Enumerable.Intersect和 Enumerable.ToDictionary

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

更新:如果仍有疑问,请阅读此内容。 Recreating a Dictionary from an IEnumerable