如何在 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
用户列表中缺少并链接到group1
和group2
必须返回 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));