Wednesday, November 9, 2022

C# linq Queries Tips and Tricks

 update multiple columns inside complex object

-------------------------------------------

  _policies = SharedFunctions.PoliciesFilterForTenant(policyTenants, _policies, _selectedTenant);

                foreach (TPolicy item in _policies)

                {

                    item.Roles = item.Roles.Select(r => { r.IsChecked = false; r.AssignmentId = 0; return r; }).ToList();

                }


---------------------------------------------------------------------

join two lists with multiple on condition

join table with custom list and get result using linq query.

 public bool UserTenantDelete(int TenantId, int GovId)

        {

            //get custom list to compare later

            List<UserTenant> TenantsToDelete = _ctx.UserTenants.Where(d => d.TenantId == TenantId && d.GovId == GovId).ToList();

            if (TenantsToDelete.Any())

            {

               List<SubjectAssignment> subjectAssignment = (from sa in _ctxPolicyServerDbContext.SubjectAssignments.ToList()

                                                             join ut in TenantsToDelete

                                                             on new {A=sa.TenantId, B=sa.SubjectId } equals new {A=ut.TenantId,B=ut.UserId.ToString()}

                                                             select  sa).ToList();

             //   _ctxPolicyServerDbContext.SubjectAssignments.RemoveRange(subjectAssignment);

               // _ctxPolicyServerDbContext.SaveChanges();

               // _ctx.SaveChanges();

                return true;

            }

            return false;


        }

-------------------------------------------------------------------------------------

Filter List using another List

   List<int> GovsNotAuthorized = _ctx.GovAgencyTenants.Where(a => a.TenantId != TenantId).Select(a=>a.GovId).ToList();
                List<int> GovsAuthorized = _ctx.GovAgencyTenants.Where(a => a.TenantId == TenantId).Select(a => a.GovId).ToList();
                List<int> result = GovsNotAuthorized.Where(x => !GovsAuthorized.Any(a => a == x)).Distinct().ToList(); 

-------------------------------------------------------------------------------------------------


No comments:

Post a Comment