0

如何在 2 个不同的列表之间找到缺失的信息

生成列表的代码

 private static IEnumerable<User> GetSomeUsers()
        {
            var mikesGroups = new List<string> { "Group1", "Group2" };
            var mike = new User { UserName = "Mike", MemberOf = mikesGroups };

            var davidsGroups = new List<string> { "Group3", "Group1" };
            var david = new User { UserName = "David", MemberOf = davidsGroups };

            return new List<User> { mike, david };
        }


        private static IEnumerable<Group> getGroups()
        {
            var group1Users = new List<string> { "Mike", "David", "Kim" };
            var group1 = new Group { Name = "Group1", Members = group1Users };

            var group2Users = new List<string> { "Mike", "David","Kim" };
            var group2 = new Group { Name = "Group2", Members = group2Users };

            return new List<Group> { group1, group2 };
        }

实体:

public class User
    {
       public string UserName { get; set; }
       public IList<string> MemberOf { get; set; } // list of group names
    }

public class Group
{
   public string Name { get; set; }
   public IList<string> Members { get; set; } // list of username
}

结果应该是 2 个列表(缺少组和缺少用户)

Group3组列表中缺少并链接到用户"David" Kim用户列表中缺少并链接到group1group2

必须返回 2 个字典 Key = 缺失值 = foundIn

Dictionary<string,IList<string>> missingUsers;
Item 1 > key="Kim", Value={"Group1","Group2"}

Dictionary<string,IList<string>> missingGroup;
item 1 > Key="Group3",{"David"}

编辑=>

我设法获取所有缺失但未链接的列表(字典中所有值的列表)

var missingGroups = users.SelectMany(g => g.MemberOf).ToList().Except(groups.Select(w => w.Name));
var missingUsers= groups.SelectMany(g => g.Members).ToList().Except(users.Select(u => u.UserName));
4

1 回答 1

0

好的,我找到了解决方案。如果您发现性能更好的更好的,请随时纠正。

        var missingGroup =
        users.ToDictionary(user => user.UserName, user => 
            user.MemberOf.Except(groups.Select(w => w.Name)))
            .Where(f => f.Value != null && f.Value.Count() > 0)
            .ToDictionary(x => x.Key, x => x.Value);
于 2013-05-02T14:51:30.340 回答