'How to filter and select a List that is an attribute of a class LINQ?

I have a Privilege

public class Privilege
{
   public virtual string Name { get; set; }
   public virtual ICollection<Role> Roles { get; set; } = new List<Role>();

}

I have a Role which contains a collection of Privilege and a corresponding UserType that the Privilege belongs to.

public class Role
{
    public virtual ICollection<Privilege> Privileges { get; set;} = new List<Privilege>();
    public virtual UserType UserType { get; set;}
}

I am trying to get a List<Privilege> from the privilege repo that only contains Privileges which have the Role I pass. My problem is kind of confusing because both classes have a collection of the other, and this codebase is very spaghetti like and cant be altered.

Here is my attempt, the issue is I cant actually get a List<Privilege> but instead get this crazy IQueryable<IEnumerable<ICollection<Privilege>>> variable back.

_privRepo.Query().Select(p => p.Roles.ToList().Where(r => r.UserType == UserType.Manager).Select(x => x.Privileges);


Solution 1:[1]

You have to refactor your code, if it is a many to many relation then there should be another class to build the relation between them.

https://docs.microsoft.com/en-us/ef/core/modeling/relationships

though you found an workaround of your query.

Solution 2:[2]

If the format is stable (always something like \d+\t\d+, so a number, followed by tab and then another number) you could do something like this

values = {sub_list[0].split('\t')[0]: sub_list[0].split('\t')[1] for sub_list in userInput}

to get a dictionary

then something like

for key, value in values.items():
    print(f'the group is {key} and their profile is {value}')

But this approach is not a good one to start with, and you would probably better served by exporting a csv or tsv file from excel and using the csv library to read the data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdullah Rana
Solution 2 Fynn