英文:
C# Is List contained in Another list?
问题
我有这个集合:
List<short> delegatingUserRoles = await (from urols in _dbContext.UsersRoles
join u in _dbContext.Users on urols.UserId equals u.UserId
where (u.Username == delegation.UserDelegating)
select urols.RoleId).Distinct().ToListAsync();
if (delegatingUserRoles.ConvertAll(i => (int)i).All(item => (delegation.UserSelectedRoles).Contains(item))){
//true
}
delegation.UserSelectedRoles
是一个包含整数的列表,是 delegatingUserRoles
的一个子集。
例如,如果 delegatingUserRoles
包含值 1、2、3、4,而 delegation.UserSelectedRoles
包含值 1、2、3,为什么它不进入条件语句?
英文:
I have this set:
List<short> delegatingUserRoles = await (from urols in _dbContext.UsersRoles
join u in _dbContext.Users on urols.UserId equals u.UserId
where (u.Username == delegation.UserDelegating)
select urols.RoleId).Distinct().ToListAsync();
if (delegatingUserRoles.ConvertAll(i => (int)i).All(item => (delegation.UserSelectedRoles).Contains(item))){
//true
}
delegation.UserSelectedRoles is a list of int, subset of delegatingUserRoles
example delegatingUserRoles has values 1,2,3,4 while
delegation.UserSelectedRoles has values 1,2,3
Why it does not enter the if?
答案1
得分: 2
"r = true"
英文:
var l1 = new List<Int32> { 1 };
var l2 = new List<Int32> { 1,2,3 };
var r = l1.All(l => l2.Contains(l));
r = true
答案2
得分: 1
"Contains"方法用于测试特定项目是否包含在列表中。它不测试列表中是否包含所有项目。您可以这样做:
if (UserSelectedRoles.All(item => delegatingUserRoles.Contains(item))
英文:
That Contains
method tests whether a specific item is contained in a list. It doesn't test whether a list of items are all contained in a list. You could do this:
if (UserSelectedRoles.All(item => delegatingUserRoles.Contains(item))
答案3
得分: 0
因为Contains()
方法检查单个对象是否包含在列表中,而不是一个列表是否包含在另一个列表中。我认为你需要在这里使用All()
。
英文:
Because the Contains()
method checks if a single object is contained within the list, not if a list is contained within another list.
I think you need All()
here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论