Home > Software engineering >  linq select from list remove other rows where condition
linq select from list remove other rows where condition

Time:12-08

I have a list like this

public class RolesAccessModel
    {
        public int Id { get; set; }
        public string PrimaryMenu { get; set; }=string.Empty;
        public string OptionMenu { get; set; } = string.Empty;
        public string Roles { get; set; } = string.Empty;
        public string UserType { get; set; } = string.Empty;
    }

The data I have in the list is like this

1,'PR','A','R','U'
2,'PR','A','R','U2'
3,'PR','A','R1','U5'
4,'PR','A','R1','U3'
5,'PR','A','R2','U6'
6,'PR','A','R2','U4'

I have 2 or more UserType values for the shortlist (PrimaryMenu, OptionMenu, Role)

I need to retrieve the shortlist (PrimaryMenu, OptionMenu, Role) where UserType is different from a specific value...

Using Linq I have this

List<RolesAccessModel> result = roleAccess.Where(p =>  p.UserType!= 'U').ToList();

It retrieves all list except ID=1

But I need to remove also the shortlist (PrimaryMenu, OptionMenu, Role) of that UserType. So ID=2 also has to be remove.

One approach is to get a list that contains the ID I want to delete, and then Exclude from the first list... the second list.

But I would like to do in just Linq operation...

It is that possible?

CodePudding user response:

Try:

List<RoleAccessModel> result = roleAccess.Where(p =>
    p.UserType != 'U'
    && !roleAccess
        .Where(p2 => p2.UserType == 'U')
        .Select(p2 => p2.Roles)
        .Contains(p.Roles)).ToList();

CodePudding user response:

I'd approach this with grouping:

roleAccess
    .GroupBy(p => (p.PrimaryMenu, p.OptionMenu, p.Roles))
    .Where(g => !g.Any(p => p.UserType == "U"))
    .SelectMany(g => g)
    .ToList();
  • Related