public Class Users
{
string UserName,
List<UserDesktop> userDesktop
}
public class UserDesktop
{
int ID,
string DesktopName,
string type -- here Type value is A, B;
}
Here I have to find the users count having desktop assigned of type A Users variable containing all data.
List<Users> finalUsers = users.Count(s=>s.userDesktop.where(x=>x.type == "A"))
Please let me know the correct way of doing it.
You might want to use SelectMany to flatten the list then count it:
int numberOfUsersWithDesktopOfTypeA = users.SelectMany(u => u.userDesktop)
.Count(ud => ud.type == "A");
If you want the list of users that have an A desktop:
var usersWithDesktopA = Users.Where(u => u.Any(ud => ud.type == "A"));
var numberOfUsersWithDesktopA = usersWithDesktopA.Count();
To query the user(s) who has UserDesktop of type 'A':
List<Users> hasDesktopAUsers = users.Where(u => u.userDesktop.Any(ud => ud.type == "A"))
.ToList();
Next, you can get the number of count from the previous result as:
int numberOfDesktopAUsers = hasDesktopAUsers.Count;
It is recommended to have a proper naming convention for handling single and plural terms to avoid confusion. For example:
public class User
{
public string UserName { get; set; }
public List<UserDesktop> UserDesktops { get; set; }
}
public class UserDesktop
{
public int ID { get; set; }
public string DesktopName { get; set; }
public string Type { get; set; }
}
From the above, you should name as User as it is an User object while UserDesktops with 's' as it is a collection set.
Final solution:
List<User> hasDesktopAUsers = users.Where(u => u.UserDesktops.Any(ud => ud.Type == "A"))
.ToList();
int numberOfDesktopAUsers = hasDesktopAUsers.Count;