计算 LINQ C# 内部列表中存在的元素数量?

Par*_*ane 1 c# linq

public Class Users{
    string UserName,
    List<UserDesktop> userDesktop
}

public class UserDesktop{
    int ID,
    string DesktopName,
    string type -- here Type value is A, B;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我必须找到分配了包含所有数据的 A 类用户变量的桌面的用户数。

List<Users> finalUsers = users.Count(s=>s.userDesktop.where(x=>x.type == "A"))
Run Code Online (Sandbox Code Playgroud)

请让我知道正确的做法

Tho*_*oub 7

您可能想使用 SelectMany 来展平列表,然后对其进行计数:

int numberOfUsersWithDesktopOfTypeA = users.SelectMany(u => u.userDesktop)
                                           .Count(ud => ud.type == "A");
Run Code Online (Sandbox Code Playgroud)

如果您想要拥有 A 桌面的用户列表:

var usersWithDesktopA = Users.Where(u => u.Any(ud => ud.type == "A"));
var numberOfUsersWithDesktopA = usersWithDesktopA.Count();
Run Code Online (Sandbox Code Playgroud)