Hi anonymous userJN
Per my test, please use following code to assign role to sharepoint online user by csom
Web web = context.Web;
Principal user = context.Web.SiteUsers.GetByLoginName(@"X");
RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Editor");
RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);
roleDefCollection.Add(readDef);
RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection);
context.ExecuteQuery();
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.