I have the following classes:
Public Class User
{
public List<SpecificUser> SpecificUsers{get;set;}
}
Public Class SpecificUser
{
public bool IsDefault{get;set;}
public List<SpecificUserRole> SpecificUserRoles{get;set;}
}
Public Class SpecificUserRoles
{
public bool IsPrimary{get;set;}
}
Requirement:Given an user object,I want to get only that SpecificUser object with IsDefault=true and which(That specific user) has 'a' SpecificUserRole with IsPrimary=true. This is what I have tried but it is returning bool instead of an instance of SpecificUser.
var defaultSpecificUser = user.SpecificUsers.Select(au => au.IsDefault && au.SpecificUserRoles.Select(aur => aur.IsPrimary).FirstOrDefault()).FirstOrDefault();
I am able to achieve it by two queries;but want to do it in one shot:
var defaultSpecificUsers = user.SpecificUsers.Where(au => au.IsDefault).ToList();
var primarySpecificUser = defaultSpecificUsers .FirstOrDefault(ddau => ddau.SpecificUserRoles.Select(aur => aur.IsPrimary).FirstOrDefault());
Any help will be highly appreciated. Thanks in advance.
CodePudding user response:
This seems simple enough:
user.SpecificUsers.Where(su => su.IsDefault == true && su.SpecificUserRoles.Any(sr => sr.IsPrimary == true));
Or simplified:
user.SpecificUsers.Where(su => su.IsDefault && su.SpecificUserRoles.Any(sr => sr.IsPrimary);
This of course assumes more than one specific user meets the criteria. If you only want one, replace Where
for First
or FirstOrDefault
if you don't know for sure if one exists.