C#中的List是否包含在另一个List中?

huangapple go评论61阅读模式
英文:

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&lt;short&gt; 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 =&gt; (int)i).All(item =&gt; (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&lt;Int32&gt; { 1 };
var l2 = new List&lt;Int32&gt; { 1,2,3 };

var r = l1.All(l =&gt; 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 =&gt; 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.

huangapple
  • 本文由 发表于 2023年4月17日 18:17:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定