如何在
中的两个不同列表之间找到缺失的信息生成列表的代码
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 = missing value = foundIn
Dictionary<string,IList<string>> missingUsers;
Item 1 > key="Kim", Value={"Group1","Group2"}
Dictionary<string,IList<string>> missingGroup;
item 1 > Key="Group3",{"David"}
编辑=&GT;
我管理得到所有遗失但未链接的列表(字典中所有值的列表)
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));
答案 0 :(得分: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);